Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why are my media files not being served in Django application with nginx?
I have a problem with my Django application which is deployed using gunicorn and nginx. I have a model for storing images in my sqlite database. class Image(models.Model): image_file = models.ImageField(upload_to="fucking_scraper/files/item_photos") item = models.ForeignKey(Item, on_delete=models.CASCADE) Here is my urls.py file urlpatterns = [ path("admin/", admin.site.urls), path("", include("fucking_scraper.urls")), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and here are parts of settings.py file, related to serving files BASE_DIR = Path(__file__).resolve().parent.parent MEDIA_URL = "/media/" MEDIA_ROOT = "" STATIC_URL = "static/" STATICFILES_DIRS = [os.path.join(BASE_DIR, "fucking_scraper", "static", "fucking_scraper"), os.path.join(BASE_DIR, "fucking_scraper", "files", "item_photos")] STATIC_ROOT = os.path.join(BASE_DIR, 'static/') On a deployed website images are not displayed. I assume there is a problem with nginx configuration because before deployment it was working correctly in a debug mode. Here is how it looks like: server { listen [::]:80; server_name fwebsite.org; location /static/ { root /home/django/fwebsite.org; } location /media/ { root /home/django/fwebsite.org/fucking_scraper/files/item_photos/; } location / { include proxy_params; proxy_pass http://unix:/home/django/fwebsite.org/fucking_website.sock; } } I tried setting up location /media/ following instructions found on the internet but it didn't work for me and I am currently stuck. -
Unable to post array in form data from react-select to django rest framework
I am building an app using React/Django and using DRF and Form data to post data from React forms to Django model. I was using React select that contains multi selections as I want to send data to manytomany field in Django models.py: class classification(models.Model): theclass = models.CharField(max_length=200) def __str__ (self): return self.theclass @property def classification_dictionary(self): return {'label':self.theclass , 'value': self.id} class book(models.Model): name = models.CharField(max_length=499) bookClassification = models.ManyToManyField('classification', blank=True) def __str__ (self): return self.name serializers.py: class BookSerializer(serializers.ModelSerializer): bookClassification = serializers.SlugRelatedField( many=True, read_only = True, slug_field='classification_dictionary' ) class Meta: model = book fields = '__all__' views.py (theapi): class BookFormViewSet(APIView): permission_classes = [AllowAny] authentication_classes = [TokenAuthentication] parser_classes = [MultiPartParser, FormParser, JSONParser] @csrf_exempt def post(self, request, format=None): serializer = BookFormSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is for the backend and the following is for the React frontend part: import React from "react"; import Select from 'react-select'; import axios from "axios"; import { useForm, Controller } from "react-hook-form"; import { TextField, Checkbox } from "@material-ui/core"; export default function BookForm(){ const [classificationOptions, setClassificationOptions] = React.useState([]) const [entryClass, setEntryClass] =React.useState([]) React.useEffect (function(){ fetch('/classification') .then(res => res.json()) .then(data => { data.map(theclass => { let newClass = {value: `${theclass.id}`, label: `${theclass.theclass}`} setClassificationOptions(oldArray => … -
Flutter Exception "type 'String' is not a subtype of type 'int' of 'index'" when fetching filtered api data
I'm making an Android app with local Django Restful Api. I have 2 models in database, that are nested together, ShowsModel and DirectorModel. This is basically how my JSON looks like with GET function. [ { "id": 1, "name": "Shows name", "annotation": "Some long text", "image": "/media/images/poster.jpg" "director": { "id": 2, "name": "First name", "surname": "Last name", "image": "/media/images/portrait.jpg" }, }, ] I need to filter shows by director id and display them. I changed up views.py in my Django, and added some functions, like check_director = self.request.query_params.get('check_director', None) if check_director: queryset = queryset.filter(director=check_director) serializer = ShowsSerializer(queryset, many=True) return Response(serializer.data) It works, now I have this key parameter check_director, and when I add value 1, it shows only that data, which contains director with id 1. Now, the problem is in Flutter. I have director detail page, that requires id, which it gets from another screen. I use this function to get data from DirectorsModel in Django Api. Future<void> getDirectorInfo() async { directorModel = await APIHandler.getDirectorsById(id: widget.id); setState(() {}); } It works, no problem. But how do I fetch data from ShowsModel? I'm trying this function for api: static Future<ShowsModel> getShowsByDirector({required String director}) async { try { var uri = … -
How do I fix these makemigrations errors?
When I try to run makemigrations it shows this error, what does it mean and how can I fix it? $ py manage.py makemigrations Traceback (most recent call last): File "C:\Users\ninie\estoque\manage.py", line 22, in <module> main() File "C:\Users\ninie\estoque\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\management\__init__.py", line 442, in execute_from_command_line utility.execute() File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\management\__init__.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\management\base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\management\base.py", line 453, in execute self.check() File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\management\base.py", line 485, in check all_issues = checks.run_checks( File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\core\checks\caches.py", line 17, in check_default_cache_is_configured if DEFAULT_CACHE_ALIAS not in settings.CACHES: File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\conf\__init__.py", line 102, in __getattr__ self._setup(name) File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\conf\__init__.py", line 89, in _setup self._wrapped = Settings(settings_module) File "C:\Users\ninie\PycharmProjects\pythonProject1\venv\lib\site-packages\django\conf\__init__.py", line 234, in __init__ raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: The ALLOWED_HOSTS setting must be a list or a tuple. It was supposed to make the migration, create tables and a file called 0001_initial.py I tried to change manage.py and settings.py, and tried to start my project from scratch but it didn't work -
How to show image link while uploading in Django?
#How to show image link while uploading in Django? This is the models.py class TopicModel(models.Model): topic_image = models.ImageField(upload_to = 'topic',blank = True,null = True) sub_catagory = models.ForeignKey(SubCatagoryModel,on_delete=CASCADE,blank = True,null = True) title = models.CharField(max_length=250) author = models.CharField(max_length=25) date_created = models.DateField(default=datetime.today) read_times = models.BigIntegerField(default=0,null=True,blank=True) blog_post = RichTextField(blank = True,null=True) def __str__(self) : return self.title class ImageModel(models.Model): image = models.ImageField(blank = True,null = True,upload_to='topic') alter = models.CharField(max_length=25,blank = True,null = True) topic = models.ForeignKey(TopicModel,on_delete=models.CASCADE) def image_link(self): return self.image.path def __str__(self) : return self.alter This is the admin.py @admin.register(ImageModel) class ImageAdmin(admin.ModelAdmin): list_display = ("image","alter","image_link") class ImageItemInline(admin.TabularInline): model= ImageModel extra = 0 @admin.register(TopicModel) class TopicAdmin(admin.ModelAdmin): list_display = ("title","author","date_created","sub_catagory","read_times") autocomplete_fields = ("sub_catagory",) search_fields = ("title",) readonly_fields = ("read_times",) inlines = [ImageItemInline] This is my admin page. When i wanna add an image in rich text editor how i will get the image link which i used in TabularInline. Is there any way to get the link from here? please suggest me some way. I have no idea how to do that on django admin. -
Hi everyone, can anyone help me?
I am coding a django project in the registration form I code in html I have 2 buttons submit and submit OTP I want when I click the send OTP button, the program will execute the send_OTP function I have coded in the view.py file, and when I click submit, I will proceed to checkOTP and register. Thanks a lot -
How to build an NFC-based smart employee in/out management system with Django?
I am working on building an employee in/out management system that utilizes NFC tags for clock-in and clock-out operations. I want to implement this system using Django, but I'm unsure about the specific steps involved. I have come across some tutorials that demonstrate similar implementations using Google Sheets example The Best Employee Timesheet using NFCs and NFC-Based Employee Time Logging System. However, I would like to integrate the system with my Django application and sync the employee database with the data stored on the NFC tags. Now I'm particularly interested in the following areas: Communication between Django app and NFC tag: I'm unsure about how to establish communication between my Django application and the NFC tags. What libraries or technologies should I use? Are there any Django-specific considerations to keep in mind? Database synchronization with NFC tag data: I want to ensure that the employee database in my Django application stays synchronized with the data stored on the NFC tags. How can I achieve this synchronization? Are there any best practices or recommended approaches? If anyone has experience with building an NFC-based employee in/out management system using Django or has insights into the specific steps I outlined, I would greatly … -
Django model constraint at least one field from two is not null or empty
I added a constraint to the model but seems that it has no impact because I'm still able to create a model instance without supplying any of the fields. Please help me to enforce the constraint to check is at least one field from two is not null or empty. Fields: class Fruit(models.Model): name1 = models.CharField(max_length=255, blank=True, null=True name2 = models.CharField(max_length=255, blank=True, null=True) class Meta: constraints = [ models.CheckConstraint( check=( Q(name1__isnull=False) | Q(name2__isnull=False) | ~Q(name1__exact='') | ~Q(name2__exact='') ), name='color_names_not_null_or_empty' ) ] Django v4 Postgres v15 -
Django IntegrityError UNIQUE constraint failed even when trying to login into Admin panel
I've searched across a similar topics but did't find a solution for my particular case. I have a User extended model and additionally UserProfile to extend and store some user's information. UserProfile has a OneToOne relation to User model. I've a User model save method overridden to instantly create a UserProfile object on User object created. But whenever I create a new User instance IntegrityError UNIQUE constraint failed: accounts_userprofile.user_id raises even though both instances created successfully (User and UserProfile). After user created (even superuser) whenever I try to login into Django Admin I got the same IntegrityError UNIQUE constraint failed: accounts_userprofile.user_id. I've tried : To apply migrations (just in case); To delete database completely and repeat everything from a scratch; I know theres is a way to change OneToOne relation to ForeignKey but I like to keep this kind of relation if there is another solution. models.py: class UserManager(BaseUserManager): def create_user(self, email, password, **kwargs): if not email: raise ValueError("Please, provide a correct email.") email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if not kwargs.get('is_staff'): raise ValueError("Superuser must have 'is_staff' value set to True") if not kwargs.get('is_superuser'): … -
Unable to generate downloadable PDF file from Django website hosted in apache
Im encountering an issue in generating a PDF file from a hosted django website. The website is hosted in apache thorough cpanel python web app. The website is basically a dashboard of all user submissions with a download button at the side. Once you click on the button, a dialog box will pop-up, prompting you to download the pdf file with user submission details. I followed this tutorial to get it to work: https://docs.djangoproject.com/en/4.2/howto/outputting-pdf/ I added some more code to it using pypdf and reportlab to handle the details from the database and add them to a pdf file to output it. The code works fine on my local computer, but when deployed to my hosting site, it returns a generic error response on my console and an uncommon error-like message saying io.UnsupportedOperation: fileno on my webapp stderr.log file. How my project is set up is that I have a javascript function that makes a GET request to a django function to generate the pdf file on the browser. Here are my code. javascript: function downloadPDF(id, date) { const csrftoken = getCookie('csrftoken'); $.ajax({ url: `/generate-pdf/${id}`, method: 'GET', headers: { 'X-CSRFToken': csrftoken, }, mode: 'same-origin', xhrFields: { responseType: 'blob' // Specify … -
How can I send both file and json data in a single request in Django using Requests library on the client side?
I need to send json data and file to my api in django. In the client side i use requests and i will share that code below. I tried this code but it gave "django.http.request.RawPostDataException: You cannot access body after reading from request's data stream". Hope you can help. client side: import requests my_json={ #some json data } file = {"file": open("sample.txt", "rb")} response = requests.post( "http://127.0.0.1:8000/API/upload-file", data=my_json, files=file ) print(response.text) endpoint in views.py def get_file(request): if request.method == "POST": uploaded_file = request.FILES["file"] json_data = json.loads(request.body) print(json_data) print(uploaded_file.filename) -
'QuerySet' object has no attribute 'items' when using HTMX get
I'm using htmx and django-filter and i want to change with hx-get and hx-target another select options but instead i got an error 'QuerySet' object has no attribute 'items' and i dont know how to fix that template.html {% render_field form.open_point_object class='form-select' hx-get='/customer/qsCategory/' hx-target='#id_category_choice' %} {% render_field form.category_choice|add_class:'form-control' %} urls.py path('customer/qsCategory/', qsCategory, name='qsCategory'), filters.py def qsCategory(request): object = request.GET.get('open_point_object') if object: return OpenPointList.objects.filter(open_point_object=object).values_list('category', flat=True).distinct() return OpenPointList.objects.values_list('category', flat=True).distinct() class OpenPointFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters['category_choice'].extra['choices'] = [ (category, category) for category in qsCategory(request=self.request) ] -
nb:i know cart models is not store any information about user , i try it but it ended with some error
Title: User Cart Data Not Persisting Across Logins in Django E-commerce Project Question: I am developing an e-commerce project using Django, and I have encountered an issue with persisting user cart data across login sessions. When a user logs in and adds products to their cart, the cart items are not visible when the user logs in again at a later time. I am unsure how to resolve this problem and would appreciate some guidance. cart view def cart_details(request,tot=0,count=0,cart_items=None,ct_items=None): try: ct=cartlist.objects.get(cart_id=c_id(request)) ct_items=items.objects.filter(cart=ct,active=True) for i in ct_items: tot += (i.prod.price*i.quan) count += i.quan except ObjectDoesNotExist: return HttpResponse("<script> alert('Empty Cart');window.location='/';</script>") return render(request,'cart.html',{'ci':ct_items,'t':tot,'cn':count}) def c_id(request): ct_id=request.session.session_key if not ct_id: ct_id=request.session.create() return ct_id def add_cart(request,product_id): prod=products.objects.get(id=product_id) try: ct=cartlist.objects.get(cart_id=c_id(request)) except cartlist.DoesNotExist: ct=cartlist.objects.create(cart_id=c_id(request)) ct.save() try: c_items=items.objects.get(prod=prod,cart=ct) if c_items.quan < c_items.prod.stock: c_items.quan+=1 c_items.save() except items.DoesNotExist: c_items=items.objects.create(prod=prod,quan=1,cart=ct) c_items.save() return redirect('cartDetails') def min_cart(request,product_id): ct=cartlist.objects.get(cart_id=c_id(request)) prod=get_object_or_404(products,id=product_id) c_items=items.objects.get(prod=prod,cart=ct) if c_items.quan>1: c_items.quan-=1 c_items.save() else: c_items.delete() return redirect('cartDetails') def cart_delete(request,product_id): ct=cartlist.objects.get(cart_id=c_id(request)) prod=get_object_or_404(products,id=product_id) c_items=items.objects.get(prod=prod,cart=ct) c_items.delete() return redirect('cartDetails') cart models class cartlist(models.Model): cart_id=models.CharField(max_length=250,unique=True) date_added=models.DateTimeField(auto_now_add=True) def __str__(self): return self.cart_id class items(models.Model): prod=models.ForeignKey(products,on_delete=models.CASCADE) #here class/tale product from shop is act as a foreign key so we can fetch the values ... cart=models.ForeignKey(cartlist,on_delete=models.CASCADE) quan=models.IntegerField() active=models.BooleanField(default=True) def __str__(self): return str(self.prod) login def register(request): if request.method == "POST": first_name = … -
Django migrate command resulting in foreign key mismatch error
Django----sqlite3.OperationalError: foreign key mismatch - "socialnetworkapp_chat" referencing "socialnetworkapp_chatroom" i have been getting error from doing performing a python manage.py migrate command, for further context i have tried reverting the migration to the previous migration where everything works fine, but after altering a few models i keep on getting this error below is the code i have in my models.py ` class ChatRoom(models.Model): chatroom_id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) created_date = models.DateField(auto_now_add=True) created_time = models.TimeField(auto_now_add=True) class Chat(models.Model): chat_id = models.AutoField(primary_key=True) chat_content = models.TextField(null=True, blank=True) created_date = models.DateField(auto_now_add=True) created_time = models.TimeField(auto_now_add=True) chatroom = models.ForeignKey(ChatRoom, on_delete=models.CASCADE) uid = models.ForeignKey(User, on_delete=models.CASCADE)` after this migration, even when i delete these models just to see if the error would resolved, the error still persists in appearing, can anyone help me detect the issue. If more context on my code is required feel free to ask, thank you. -
handle Generic Model saving with signal django
Here is my code erp/partner/models.py class BimaErpPartner(AbstractModel): GENDER_CHOICES = [(gender.value, gender.name) for gender in Gender] STATUS_CHOICES = [(status.value, status.name) for status in EntityStatus] PARTNER_TYPE_CHOICES = [(partner_type.value, partner_type.name) for partner_type in PartnerType] COMPANY_TYPE_CHOICES = [(company_type.value, company_type.name) for company_type in CompanyType] is_supplier = models.BooleanField(blank=True, null=True) is_customer = models.BooleanField(blank=True, null=True) partner_type = models.CharField(max_length=128, blank=False, null=False) company_type = models.CharField(max_length=256, blank=False, null=False) first_name = models.CharField(max_length=128, blank=False) last_name = models.CharField(max_length=128, blank=False) gender = models.CharField(max_length=32, blank=True, choices=GENDER_CHOICES) social_security_number = models.CharField(max_length=64, blank=False, null=False) id_number = models.CharField(max_length=64, blank=False, null=False) Email = models.EmailField(blank=True, null=True) Phone = models.CharField(blank=True, null=True) Fax = models.CharField(blank=True, null=True) company_name = models.CharField(blank=True, null=True) company_activity = models.CharField(blank=True, null=True) vat_id_number = models.CharField(blank=True, null=True) status = models.CharField(max_length=32, blank=True, null=True, choices=STATUS_CHOICES) note = models.CharField(blank=True, null=True) addresses = GenericRelation(BimaCoreAddress, related_name='addresses') contacts = GenericRelation(BimaCoreContact, related_name='contacts') documents = GenericRelation(BimaCoreDocument, related_name='documents') in erp/partner/signals.py @receiver(post_save, sender=BimaErpPartner) @transaction.atomic def create_partner_related_entities(sender, instance, created, **kwargs): print("aaaa") if created: addresses_data = instance.address_data if addresses_data: addresses = create_addresses(addresses_data, instance) BimaCoreAddress.objects.bulk_create(addresses) contacts_data = getattr(instance, 'contact_data', []) if contacts_data: contacts = create_contacts(contacts_data, instance) BimaCoreContact.objects.bulk_create(contacts) documents_data = getattr(instance, 'document_data', []) if documents_data: documents = create_documents(documents_data, instance) BimaCoreDocument.objects.bulk_create(documents) def create_addresses(addresses_data, partner): addresses = [] for address_data in addresses_data: address_serializer = BimaCoreAddressSerializer(data=address_data) address_serializer.is_valid(raise_exception=True) address = address_serializer.save(entity=partner) addresses.append(address) return addresses def create_contacts(contacts_data, partner): contacts = [] for … -
Problem with memory when I try to deploy my xgboost models on heroku
I have deployed five xgboost models on heroku using django. After success deployment I have received the next message: Warning: Your slug size (321 MB) exceeds our soft limit (300 MB) which may affect boot time. But the max available size is 500 MB. And as a result my app doesn't work correctly. For example my css styles can't be upload and when I try to go to an other page of my app it crashes with message: So how can I solve this problem? For your information the biggest object is xgboost liblary. -
how to extract data from queryset with django filter
yes_limit = Yes_Limitorder_Quantity.objects.filter(event_id = id) Yes_limit = {"yes_amount1":1, "yes_amount2":4, "yes_amount3" : 0, "yes_amount4":2, "yes_amount5":0} I'm using filter following data me expected: Yes_Limit = {"yes_amount1":1, "yes_amount2":4,"yes_amount4":2} -
Why do I keep getting an 'object of type method has no len()' error when using Django's pagination?
Been trying to figure out why do I keep getting *"object of type 'method' has no len()", where it directs me to this line. Please help I've been at it for the past 3 days and i really want to pull my hair out. from django.core.paginator import Paginator def index(request): allPosts = Post.objects.all().order_by("id").reverse #paginator paginator = Paginator(allPosts, 10) page_number = request.GET.get('page') *posts_of_page = paginator.get_page(page_number)* return render(request, "network/index.html", { "allPosts" : allPosts, "posts_of_page" : posts_of_page, }) -
How To Run Discord bot inside Django and use signals with it
So I have created my django website and. I want to run my discord bot inside my django website And also **can I use the signals to send a message on my server if post have been crated ** So any one can help me how to do that -
Default content-type for Django test client
I am trying to make application/json the default content type of the Django test client. I am wondering if there is a smarter way than this: from functools import partial c = Client() c.post = partial(c.post, content_type="application/json") I tried Client(content_type="application/json") and Client(HTTP_CONTENT_TYPE="application/json") but neither of them worked. -
How to fix bug when multiple accordions open in Bootstrap when quickly switching between them?
I'm trying to implement an accordion using bootstrap, where when a button is clicked, a collapse show occurs. It is important to understand that when one collapse is opened, the other must be closed. And it seems to work that way, but if I start switching between them quickly, I catch a bug where I have two collapse open at the same time. The Bootstrap documentation says that to achieve this effect, you need to specify the same data-bs-target, but as you can see from my code, this aspect is taken into account. Below I will attach all the required code, as well as a video with a demonstration of this bug. HTML <div class="container"> <div class="accordion" id="accordion"> <div class="steps"> <div class="step-item mx-auto"> {% for step in steps %} {% if step.id == 1%} <button class="step-button text-center" type="button" data-bs-toggle="collapse" data-bs-target="#Step{{ step.id }}" aria-expanded="true" aria-controls="collapse{{ step.id }}"> {{ step.id }} </button> {% else %} <button class="step-button text-center" type="button" data-bs-toggle="collapse" data-bs-target="#Step{{ step.id }}" aria-expanded="false" aria-controls="collapse{{ step.id }}" > {{ step.number_step }} </button> {% endif %} {% endfor %} </div> </div> <div class="card "> {% for step in steps %} {% if step.id == 1 %} <div id="Step{{ step.id }}" class="collapse show" data-bs-parent="#accordion"> … -
HTMX does not send new values in select
I'm using htmx and django-filter and i want to change with hx-get and hx-target another select values but instead i got blank options in select template.html {% render_field form.open_point_object class='form-select' hx-get='/customer/open-point-list/' hx-target='#id_category_choice' %} {% render_field form.category_choice|add_class:'form-control' %} urls.py path('customer/presence-info/', CustomerPresenceInfoList.as_view(), name='customer_presence_info'), filters.py def qsCategory(request): object = request.GET.get('open_point_object') if object: return OpenPointList.objects.filter(open_point_object=object).values_list('category', flat=True).distinct() return OpenPointList.objects.values_list('category', flat=True).distinct() class OpenPointFilter(django_filters.FilterSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.filters['category_choice'].extra['choices'] = [ (category, category) for category in qsCategory(request=self.request) ] after changing value in open_point_object i got this in category_choice select -
Is there a way to process values passed from React in django and then send them back to React?
I'm cooperating with my friend to make toy project using Django RESTful api and React. I'm doing with django. This is my simplified model.py: class Map(models.Model): name = models.CharField(max_length=50) monsters = models.ManyToManyField('Monster', blank=True, related_name='maps') def __str__(self): return self.name class Quest(models.Model): name = models.CharField(max_length=50) goal = models.TextField() recommended_map = models.ManyToManyField(Map, related_name='quests') def __str__(self): return self.name I completed to pass quest list to react side using api. Users can select several quests from that list. What I want to do is finding a recommened_map that the user selected quest has in common and sending it back to React. I've searched all day but I couldn't. Is it impossible? -
How to make Django present generated mp4
I have a docker volume that contains generated mp4 files. I want to find a way to display them in dev because my current solution results in an error. error Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/fergana_api/files/36/movies/movie.mp4 Using the URLconf defined in fergana_api.urls, Django tried these URL patterns, in this order: admin/ api/schema/ [name='api-schema'] api/docs/ [name='api-docs'] api/ [name='all-runs'] tests/<slug:test_session_id> [name='single-run'] tests/<slug:test_session_id>/<slug:test_name> [name='single-test'] ^static/(?P<path>.*)$ ^files/(?P<path>.*)$ The current path, fergana_api/files/36/movies/movie.mp4, didn’t match any of these. You’re seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. settings.py STATIC_URL = 'static/' MEDIA_URL = 'files/' MEDIA_ROOT = '/var/web/media/' STATIC_ROOT = BASE_DIR / 'static_files' # location of static files STATICFILES_DIRS = [ BASE_DIR / 'static' ] app/views.py class SingleTestView(View): def get(self, request, test_session_id, test_name): run = Runner.objects.get(id=test_session_id) path_to_session = to_file('files/', f'{test_session_id}') movies_dir_path = to_file(path_to_session, 'movies') movie_path = to_file(movies_dir_path, test_name.replace('-', '_') + '.mp4') context = { 'movie_path': movie_path } return render(request, "presenter/single_test.html", context) project/url.py if settings.DEBUG: urlpatterns += static( settings.STATIC_URL, document_root=settings.STATIC_ROOT ) urlpatterns += static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) single_test.html <video width="320" height="240" controls> <source src="{{ movie_path }}" type="video/mp4"> </video> It seems like the app uses the correct … -
Access Data in the Template from the Junction Model
I´m Trying to Access Data from my "junction" model clientvul in my Template. models.py from django.db import models from django.contrib import admin class client(models.Model): client= models.CharField(max_length=50,primary_key=True) user= models.CharField(max_length=100) vuls = models.ManyToManyField( 'vul', through='clientvul', related_name='client' ) class vul(models.Model): vid=models.IntegerField(primary_key=True) cvelist=models.CharField(max_length=50) cvsscore=models.FloatField(max_length=5) serverity=models.CharField(max_length=25) title=models.CharField(max_length=1000) summary=models.CharField(max_length=1000) class clientvul(models.Model): client= models.ForeignKey(client, on_delete=models.CASCADE) vid=models.ForeignKey(vul, on_delete=models.CASCADE) path=models.CharField(max_length=1000) isactive=models.BooleanField(default=True) class Meta: constraints = [ models.UniqueConstraint( fields=['client', 'vid'], name='unique_migration_host_combination' ) ] admin.site.register(client) admin.site.register(vul) admin.site.register(clientvul) views.py def index(request): qs = client.objects.prefetch_related('vuls') return render(request, 'browseDB.html', {'data':qs}) Template {% for row in data %} <table class="table"> <thead class="table-dark"> <tr> <th scope="col">Hostname</th> <th scope="col">User</th> </tr> </thead> <tbody> <td class="Hostname">{{ row.client }}</a></td> <td class="User">{{ row.user }}</td> </tbody> </table> <table class="table"> <thead> <tr> <th scope="col">Title</th> <th scope="col">Severity</th> <th scope="col">CVE</th> <th scope="col">Path</th> </tr> </thead> <tbody> {% for subitem in row.vuls.all %} <tr> <td class="Title" >{{ subitem.title }}</td> <td class="Severity">{{ subitem.serverity }}</td> <td class="CVE" >{{ subitem.cvelist }}</td> <td class="Path" >{{ subitem.path }}</td> </tr> {% endfor %} </tbody> </table> <br> {% endfor %} The problem is that <td class="Path" >{{ subitem.path }}</td> stays empty. I don´t know how I can reference the related path from the junction Model clientvul. Related Question: Django prefetch_related with 3 not directly related Models