Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django websocket website returning an empty JSON/dictionary when I try to reference the user's username
I am building a django website where users can chat with each other and I am using channels for its development. I intended on programming it in such a way that the user's profile pic would be beside their message with their username on top of their message. But right now, I am not seeing their profile photo nor their username. I am just getting the alt text instead of their profile photo, and a '{}' beside their username. I have added console.log() and print() statements in various places inside of my code for debugging it which I will show in the output. The following is routing.py: from django.urls import re_path from . import consumers websocket_urlpatterns = [ re_path(r'^ws/chat/(?P<room_name>\w+)/$', consumers.ChatRoomConsumer.as_asgi()) ] The following is views.py: from django.shortcuts import render, redirect from django.contrib import messages from django.http import HttpResponse from django.http import JsonResponse from django.contrib.auth.models import User from users.models import Profile def home(request): context = { } return render(request, 'common_anime_chat/index.html', context) def about(request): return render(request, 'common_anime_chat/about.html') def room(request, room_name): if request.user.is_authenticated: return render(request, 'common_anime_chat/chatroom.html', { 'room_name':room_name }) else: messages.success(request, f'You need to log in to start conversations.') return redirect('login') def get_user_profile_pictures(request): # Get all users profiles = Profile.objects.all() # Create a … -
Can't figure out how to get rid of field required message on Django form submission
I have a model form that has a name field and when I submit the form, I get the 'field required' message even when the name field is filled out. models.py from django.db import models from user.models import User class Image(models.Model): """This model holds information for user uploaded images""" # Status of the image class Status(models.TextChoices): PUBLIC = 'public', 'Public' PRIVATE = 'private', 'Private' name = models.CharField(max_length=150) image = models.ImageField(upload_to='images/') status = models.CharField( max_length=7, choices=Status.choices, default=Status.PUBLIC) upload_date = models.DateTimeField(auto_now_add=True) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='photos') def __str__(self) -> str: return self.name class Meta: indexes = [ models.Index(fields=['name'], name='name_idx'), models.Index(fields=['user'], name='user_idx') ] ordering = ['-upload_date'] forms.py from django import forms from .models import Image from utils.forms.widgets import text_input, select_input, image_input class ImageUploadForm(forms.ModelForm): """Use this form to upload images""" class Meta: model = Image fields = [ 'name', 'image', 'status', ] widgets = { 'name': text_input, 'image': image_input, 'status': select_input, } The Error that I'm getting That's after trying to submit the form with an image selected and the name filled out. I have tried using the clean_name method to see if returning the name of the image would fix it but to no avail. -
Custom Form Wizard bootstrap 5
I currently develop custom form wizard using bootstrap 5 and jquery. Not using any plugin. Here my html code : <div class="card-inner"> <form action="{% url 'toTANewPrj' %}" method="post" id="frmNewPrj" class="form-validate is-alter"> {% csrf_token %} <div class="row"> <div class="col-md-4"> <ul class="custom-stepper"> <li class="custom-step active" data-step-number="1"> <div> <div class="lead-text">Intro</div> <div class="sub-text">Define your project type and audit year.</div> </div> </li> <li class="custom-step" data-step-number="2"> <div> <div class="lead-text">Profiles</div> <div class="sub-text">Define your project type and audit year.</div> </div> </li> <li class="custom-step" data-step-number="3"> <div> <div class="lead-text">Intro</div> <div class="sub-text">Define your project type and audit year.</div> </div> </li> </ul> </div> <div class="col-md-8"> <div class="custom-step-content active"> page 1 </div> <div class="custom-step-content"> <h5>Project Details</h5> <div class="row g-3"> <div class="col-12"> <div class="form-group"> <label class="form-label" for="PrjName">Project Name</label> <div class="form-control-wrap"> <div class="input-group"> <input type="text" class="form-control" id="PrjName" name="PrjName" placeholder="Name your project here" required> <div class="input-group-append"> <span class="btn btn-success btn-dim" data-bs-toggle="tooltip" data-bs-placement="top" title="Get from Teammate" onclick="showModalPrjTM()"> <em class="icon ni ni-download"></em> </span> </div> </div> </div> </div> </div> </div> </div> <div class="custom-step-content"> page 3 </div> <div class="navigation-buttons"> <button class="btn btn-dim btn-success" id="prevBtn" onclick="prevStep()">Previous</button> <button class="btn btn-success" id="nextBtn" onclick="nextStep()">Next</button> <button type="submit" class="btn btn-success" id="submitBtn">Submit</button> </div> </div> </div> </form> </div> And here my css : .custom-stepper { list-style-type: none; padding: 0.5rem; display: flex; flex-direction: column; } .custom-stepper > *.custom-step { … -
Store adresses in database
I'm doing a project on Django and I need to store addresses in the database (country, city, street, house). What is the best way to do this? I was thinking of storing the country, city, street and house separately. Are there any other ways to do this? -
How to properly dynamically add ModelForm fields with django-modeltranslation enabled?
I'm attempting to dynamically add translatable fields for my forms.ModelForm, depending on whether the customer has enabled the language or not. However, the translated value isn't saved to the model. class DefaultModelForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if user := self.request and self.request.user: company = user.company app_setting = company.settings default_lang = settings.MODELTRANSLATION_DEFAULT_LANGUAGE # "en" default_search = f"_{default_lang}" to_add = [] """Set field_order to the same order as set in Meta.fields, unless already set""" if self.field_order is None: self.field_order = list(self.Meta.fields) for modelfield in self._meta.model._meta.fields: """If we found a default translation field, add it to the list""" if ( (formfield := self.fields.get(modelfield.name, None)) and modelfield.name.endswith(default_search) and isinstance(modelfield, TranslationField) ): to_add.append( { "position": self.field_order.index(modelfield.name), "formfield": deepcopy(formfield), "name": modelfield.name.removesuffix(default_search), # "description" "languages": app_setting.get_additional_language_codes, # ["es"] } ) for addable in to_add: for lang in addable.get("languages"): field_name = f"{addable.get('name')}_{lang}" # "description_es" formfield = addable.get("formfield") formfield.label = formfield.label.replace(f"[{default_lang}]", f"[{lang}]") formfield.required = False formfield.initial = getattr(self.instance, field_name, "") self.fields[field_name] = formfield self.field_order.insert(addable.get("position", 0) + 1, field_name) self.order_fields(self.field_order) This code allows me to render the fields accordingly. If the customer has selected to show e.g. "es" (Spanish), the translatable field ("description_en") will be copied and I create a new field ("description_es") in the right position inside … -
Django is not sending email with the SMTP server of mail.ru
I am facing with a problem of sending emails on Django. I think that my settings, views and model is correct, but despite of that mail is not sending. There is no problem when I try this on console Django version == 4.2.1 Python version == 3.10 settings.py: `EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = 'smtp.mail.ru' EMAIL_PORT = 465 EMAIL_HOST_USER = 'storedjango@mail.ru' EMAIL_HOST_PASSWORD = '*****' EMAIL_USE_SSL = True` models.py: `class EmailVerification(models.Model): code = models.UUIDField(unique=True) user = models.ForeignKey(to=User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) expiration = models.DateTimeField() def __str__(self): return f'Email verification for user {self.user.email}' def send_verification_email(self): link = reverse('users:email_verification', kwargs={'email': self.user.email, 'code': self.code}) verification_link = f'{settings.DOMAIN_NAME}{link}' subject = f'Verification for {self.user.username}' message = f'Click to the link to verify your account {self.user.email} {verification_link} ' send_mail( subject=subject, message=message, from_email=settings.EMAIL_HOST_USER, recipient_list=[self.user.email], fail_silently=False ) def is_expired(self): return True if now() >= self.expiration else False` views.py: `class EmailVerificationView(TemplateView): template_name = 'users/email_verification.html' def get(self, request, *args, **kwargs): code = kwargs['code'] user = User.objects.get(email=kwargs['email']) email_verifications = EmailVerification.objects.filter(user=user, code=code) if email_verifications.exists() and not email_verifications.first().is_expired(): user.is_verified_email = True user.save() return super(EmailVerificationView, self).get(request, *args, **kwargs) else: return HttpResponseRedirect(reverse('index'))` forms.py: ` def save(self, commit=True): user = super(UserRegistrationForm, self).save(commit=True) expiration = now() + timedelta(hours=48) record = EmailVerification.objects.create(code=uuid.uuid4(), user=user, expiration=expiration)` What could be causing as the … -
Not able to access image uploaded through HTML forms
This is my class that I have created in models.py. class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) vendor = models.ForeignKey(Vendor, related_name='products', on_delete=models.CASCADE,blank=True,null=True) name = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(blank=True, null=True) price = models.DecimalField(max_digits=6, decimal_places=2) vegetarian = models.BooleanField(default='True') created_at = models.DateTimeField(auto_now_add=True) image = models.ImageField(upload_to='uploads/',blank=True,null=True) thumbnail = models.ImageField(upload_to='uploads/', blank=True, null=True) This is my forms.py from django.forms import ModelForm from product.models import Product class ProductForm(ModelForm): class Meta: model = Product fields = ['category','image','name','description','price'] This is my form in html file: <form method="post" action="."> {% csrf_token %} {{ form.as_p }} <div class="field"> <div class="control"> <button class="button is-dark is uppercase">Submit</button> </div> </div> </form> But when I run server, I am not able to see the image of my product while I am able to see the other details that I want as given in this frontpage.html file: {% for product in products %} <li>{{product.name}}</li> <li>{{product.price}}$</li> <li>{{product.description}}</li> <li><figure><img src="{{ product.get_thumbnail }}"></figure></li> {% endfor %} Please explain why so? I want to see images on my frontpage too. When I fill the form to add products, I upload the image and fill other details, but only text details are visible and not image. -
How to solve TypeError at /AddUser/ AddUser() got an unexpected keyword argument 'username' Error for accessing Django Database
I am getting this error: TypeError at /AddUser/ AddUser() got an unexpected keyword argument 'username' when trying to connect to Django Database enter image description here My views.py File enter image description here Urls.py enter image description here Models.py enter image description here Base.html enter image description here Settings.py enter image description here enter image description here Full Traceback: C:\Users\Riya\PycharmProjects\pythonProject2\venv\Lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ … Local vars C:\Users\Riya\PycharmProjects\pythonProject2\venv\Lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … Local vars C:\Users\Riya\PycharmProjects\pythonProject2\career\career\views.py, line 13, in AddUser new_user = AddUser (username=username,password=password,phone=phone) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … Local vars What should i do to solve this error? I tried making changes in views.py file but its still showing me the same error -
Django+Htmx: get the selected item of a combobox (created with Htmx) and print it?
I need to get the selected element of the combobox with function def trips. Then use it in the def result function which is used to print the selected item in textarea. The button request is only used to display the data (in the textarea). P.S: If you're wondering, the trip_selector function is that of the first combobox that is dependent. views.py def trip_selector(request): countries = Trip.objects.values_list('country', flat=True).distinct() trips = [] # no trips to start with return render(request, 'form.html', {"countries": countries, "trips": trips}) def trips(request): country = request.GET.get('country') trips = Trip.objects.filter(country=country) return render(request, 'trips.html', {"trips": trips}) def result(request): test_print_in_result = trips return render(request,"result.html", {"test_print_in_result": test_print_in_result}) In the other files everything is ok, I need help only in views.py UPDATE form.py {% extends 'base.html' %} {% block content %} <!-- First Combobox --> <label for="id_country">Country</label> <select name="country" id="id_country" hx-get="{% url 'trips' %}" hx-swap="outerHTML" hx-target="#id_trip" hx-indicator=".htmx-indicator" hx-trigger="change"> <option value="">Please select a country</option> {% for country in countries %} <option value="{{ country }}">{{ country }}</option> {% endfor %} </select> <!-- Second Combobox ??????? (non lo so)--> <label for="id_trip">Trip</label> {% include "trips.html" %} <!-- Textarea--> {% include "result.html" %} <!-- Button--> <button type="button" class="mybtn" name="btn" hx-get="{% url 'result' %}" hx-swap="outerHTML" hx-target="#id_result" hx-indicator=".htmx-indicator">Button 1</button> … -
Bootstrap : nav menu toggle blocked unrolled
I am creating a project using several things : psycopg2 to query a SQL database pandas to model the data bokeh to create graphics django for the back-end bootstrap for the front-end I'm discovering the front-end, using the system of links in or tags to retrieve the CSS and JS elements needed to make bootstram work, as indicated on the offical website. However, I don't understand why : The menu that appears when the screen size shrinks opens but I can't close it. The only thing that work to untoggle it is to reload the page... Do you know what the problem could be? Here are the elements I've added, as indicated in the section: <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>My Website</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-9ndCyUaIbzAi2FUVXJi0CjmCapSmO7SnpJef0486qhLnuZ2cdeRhO02iuK6FUUVM" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js" integrity="sha384-Atwg2Pkwv9vp0ygtn1JAojH0nYbwNJLPhwyoVbhoPwBhjQPR5VtM2+xf0Uwh9KtT" crossorigin="anonymous"></script> </head> And at the end of the body section: <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-geWF76RCwLtnZ8qwWowPQNguL3RmwHVBC9FhGdlKrxdiJJigb/j/68SIy3Te4Bkz" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.min.js" integrity="sha384-fbbOQedDUMZZ5KreZpsbe1LCZPVmfTnH7ois6mU1QK+m14rQ1l2bGBq41eYeM/fS" crossorigin="anonymous"></script> </body> This is what it actually look like, on small screen (mobile like) : https://ibb.co/6DyXLhb With the toggle menu unrolled, I can't collapse it. The dropdown menu corresponding to "dashboards" doesn't work whatever the screen size.: https://ibb.co/hRbbrhL -
Django ORM returns all data in many-to-many key relationship
I am facing this problem when i apply .filter() on Django model it return all the sales data which i dont want, I am trying to filter data based on date and want data of the entered date only Sales Model: class Sales(models.Model): Amount = models.FloatField(blank=True, null=True) Date = models.DateField() updated_at = models.DateTimeField(auto_now=True) VAT = models.BooleanField(default=True) Machine Model: class Machine(models.Model): name = models.CharField(max_length=50) Sales = models.ManyToManyField(Sales, blank=True) ...... API: class MachineDateData(APIView): def post(self, request): target_date = date(2023, 5, 1) data = Machine.objects.filter(id=524).filter(Sales__Date=target_date) serializer = MachineReadOnlySerializer(data, many=True) return Response(serializer.data) Serializer: class MachineReadOnlySerializer(serializers.ModelSerializer): class Meta: model = Machine depth = 1 fields = ('id','name', 'Sales') Result: [ { "id": 524, "name": "Résidhome Marseille Saint Charles ", "Sales": [ { "id": 67274, "Amount": 45.12327285161129, "Date": "2023-05-01", "updated_at": "2023-07-29T19:08:07.702463Z", "VAT": false }, { "id": 67275, "Amount": 43.24381640146215, "Date": "2023-05-02", "updated_at": "2023-07-29T19:08:07.725326Z", "VAT": false }, { "id": 67276, "Amount": 85.53046658140136, "Date": "2023-05-03", "updated_at": "2023-07-29T19:08:07.747431Z", "VAT": false }, ...more results here } ] I am looking for a result that looks like this, Inner join to both tables, I have tried to on SQL and on SQL it works fine and shows result, but in Django ORM it does show all the data [ { "id": … -
Why ZADD command not working in Django-app?
I want to realize in my Django blog «Top 5 trend post». For this purpose, I implemented a Cron task that calls the function update_trends() once a day. This function should reset hits counter in Redis db. Hits counter is a Sorted Set with the structure: setname ("hits") score (hits amount) key (post id) Here is the function: def update_trends(): # deleting the counter with click statistics for the previous day r.delete('hits') # ،Assigning a zero value for each post id articles_ids = Article.objects.values_list('pk', flat=True) for article_id in articles_ids: r.zadd('hits', 0, article_id) r variable are initialized above in global scope: r = redis.Redis(host='localhost', port=6379, db=0) Article class imported like this: from .models import Article When Cron fires, the sorted set "hits" is removed, but for some reason zero values for each post id are not written. I can't understand why? If I manually write in shell: redis-cli zadd hits 0 1 Then the value is successfully set. Also I have tried to use in update_trends() such way: articles = Article.objects.all() for article in articles: r.zadd('hits', 0, article.pk) But it doesn't work too. -
Nginx does not serve static files
I am new to web-dev and have a problem with deploying web-app with Django and React on Nginx and gunicorn. For some reason it does not serve static files. I don't have a real IP-address for the server so Nginx is on localhost. It also maybe that I have some problem with my docker configuration. So here is the Nginx.conf: server { listen 80; server_name localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/rroxxxsii/PycharmProjects/web-for-cyclers/backend; } location /media/ { autoindex on; autoindex_exact_size off; root /home/rroxxxsii/PycharmProjects/web-for-cyclers/backend; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Nginx Dockerfile: FROM nginx:1.24.0-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d Docker compose: services: # Django web-backend: build: ./backend volumes: - .:/backend - static_volume:/backend/static - media_volume:/backend/media ports: - '8000:8000' env_file: - backend/web.env image: backend container_name: django_cycle_api command: > bash -c "cd ./backend && ./manage.py collectstatic --noinput && ./manage.py migrate && gunicorn -b 0.0.0.0:8000 core.wsgi:application" depends_on: - db # PostgreSQL db: image: postgres:14.1-alpine restart: always env_file: - backend/web.env ports: - '5432:5432' volumes: - db:/var/lib/postgresql/data # React web-frontend: container_name: cycle_frontend build: ./frontend expose: - 3000 command: serve -s /usr/src/app/build -l 3000 depends_on: - web-backend ports: - '3000:3000' # Nginx nginx: image: nginx depends_on: … -
form with multiple image value return list object has no attribute _committed when I try to submit it
I have a form inside my forms.py file when I try to submit the form it throws me an error: 'list' object has no attribute '_committed'. In that form, I want to allow user to upload multiple image in one model field, for that I have to follow this documentation, but I don't have an idea why it's throws the error every time I try to submit it. model class LevelType(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) images = models.FileField(upload_to='images-level') ``` ``` ``` forms.py class MultipleFileInput(forms.ClearableFileInput): allow_multiple_selected = True class MultipleFileField(forms.FileField): def __init__(self, *args, **kwargs): kwargs.setdefault("widget", MultipleFileInput()) super().__init__(*args, **kwargs) def clean(self, data, initial=None): single_file_clean = super().clean if isinstance(data, (list, tuple)): result = [single_file_clean(d, initial) for d in data] else: result = single_file_clean(data, initial) return result class LevelTypesForms(forms.ModelForm): images = MultipleFileField() class Meta: model = LevelType fields = [ 'level', 'bank_name', 'account_number', 'account_name', 'images', 'price', 'currency', 'description', 'accept_payment_with_card', ] views.py: class CreateLevelType(CreateView): model = LevelType form_class = LevelTypesForms success_url = reverse_lazy('Level-Types') template_name = 'Account/create_level_type.html' def get_form(self, form_class=None): form = super().get_form(form_class) form.fields['level'].queryset = Level.objects.filter(user=self.request.user) return form def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.instance.user = self.request.user form.save() images = form.cleaned_data["images"] … -
Django blog comment functionality with Jquery not working, takes me to JSON page instead
So i am building a blog with Django and I am trying to implement a comment functionality with JQuery to avoid a page refresh. I've written the codes but when I click on the comment submit button, I get sent to a white page with JSON data. I've struggled with this problem for too long and i'm hoping for a solution here. Following are the relevant codes. in my detail page, this is the html for the comment form: <div id="comment-container" class="comment-container" style="display: none;"> <form id="comment-form" method="post" action="{% url 'article:comment_submit' post.slug %}"> {% csrf_token %} <textarea id="comment-textarea" style="font-size: 16px; color: #333; background-color: #f2f2f2; border: 1px solid #ccc; border-radius: 4px; padding: 8px; outline: none; text-align:left;" name="comment" rows="4" cols="50"> </textarea> <button id="submit-comment" style="display: block;" type="button">Submit</button> </form> </div> still in my detail page is an empty div tag where I intend to prepend/append the comments: <div id="comments-section"> </div> in my main.js, I have: $(document).ready(function() { // Function to submit the comment form using AJAX $("#submit-comment").on("click", function(event) { event.preventDefault() var commentText = $("#comment-textarea").val().trim(); if (commentText !== "") { var formData = $("#comment-form").serialize(); // Get the comment submission URL from the data attribute var commentSubmitURL = "{% url 'article:comment_submit' post.slug %}"; $.ajax({ type: "POST", url: … -
an error is displayed OSError at /images/create/[Errno 38] Function not implementedRequest Method:POST
here is the form code: from django import forms from .models import Image from django.core.files.base import ContentFile from django.utils.text import slugify import requests class ImageCreateForm(forms.ModelForm): class Meta: model = Image fields = ['title', 'url', 'description'] widgets = { 'url': forms.HiddenInput, } def clean_url(self): url = self.cleaned_data['url'] valid_extensions = ['jpg', 'jpeg', 'png'] extension = url.rsplit('.', 1)[1].lower() if extension not in valid_extensions: raise forms.ValidationError('The given URL does not ' \ 'match valid image extensions.') return url def save(self, force_insert=False, force_update=False, commit=True): image = super().save(commit=False) image_url = self.cleaned_data['url'] name = slugify(image.title) extension = image_url.rsplit('.', 1)[1].lower() image_name = f'{name}.{extension}' # download image from the given URL response = requests.get(image_url) image.image.save(image_name, ContentFile(response.content), save=False) if commit: image.save() return image here is the views.py: from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from django.shortcuts import get_object_or_404 from django.http import JsonResponse from django.views.decorators.http import require_POST from django.http import HttpResponse from django.core.paginator import Paginator, EmptyPage, \ PageNotAnInteger from .forms import ImageCreateForm from .models import Image @login_required def image_create(request): if request.method == 'POST': # form is sent form = ImageCreateForm(data=request.POST) if form.is_valid(): # form data is valid cd = form.cleaned_data new_image = form.save(commit=False) # assign current user to the item new_image.user = request.user new_image.save() messages.success(request, … -
Ubuntu UWSGI Permission Denied
I am doing the command : sudo supervisorctl update sudo supervisorctl status This is the response i get from running the command bridged RUNNING pid 9808, uptime 0:01:57 celery RUNNING pid 9809, uptime 0:01:57 site FATAL Exited too quickly (process log may have details) Here is my site.conf code, this site.conf is supposed to run under django environment, in my webEnv environment there is the uwsgi runner. The uwsgi is used as worker for online judge website. [program:site] command=/home/jeff/webEnv/bin/uwsgi --ini uwsgi.ini directory=/home/jeff/site stopsignal=QUIT stdout_logfile=/tmp/site.stdout.log stderr_logfile=/tmp/site.stderr.log So i try checking the site.stderr.log, and here what the response said about the code. detected number of CPU cores: 3 current working directory: /home/jeff/site writing pidfile to /tmp/dmoj-site.pid open("/tmp/dmoj-site.pid"): Permission denied [core/utils.c line 3>[uWSGI] getting INI configuration from uwsgi.ini *** Starting uWSGI 2.0.22 (64bit) on [Sun Jul 30 13:29:09 2023] ***compiled with version: 11.3.0 on 29 July 2023 17:26:29 os: Linux-5.19.0-50-generic #50-Ubuntu SMP PREEMPT_DYNAMIC Mon Jul>nodename: Ubuntu machine: x86_64 clock source: unix detected number of CPU cores: 3 current working directory: /home/jeff/site writing pidfile to /tmp/dmoj-site.pid open("/tmp/dmoj-site.pid"): Permission denied [core/utils.c line 3> My uwsgi.ini code is like this. [uwsgi] # Socket and pid file location/permission. uwsgi-socket = /tmp/dmoj-site.sock chmod-socket = 666 pidfile = /tmp/dmoj-site.pid … -
Understanding reusable apps in Django
I am building a backend REST API using Django and Django-rest-framework for venues to sell tickets and fans to book seats. So far, I have a monolith app called 'concert', which contains all my models.py, serializers.py, and views.py. Each of these files now has 1000+ lines, so I'm thinking about how to split my code into smaller chunks. I watched James Bennett's Reusable Apps talk, but I don't understand why anyone would create reusable apps. For example, I have two models Concert and ConcertTicket. Obviously ConcertTicket has a ForeignKey reference to Concert, and so the model relationship flows in this direction. On the other hand, inside serializers, ConcertSerializer depends back on ConcertTicketSerializer, since I am using the latter as a nested serializer. It seems like if I separate this into a concert and ticket app, I will have a really weird dependency where ticket.models depends on concert.models, but concert.serializers depends on ticket.serializers. I won't be able to share my app to the Django community because of how specialized it is to the industry, so I cannot see why anyone would try to create reusable apps at all. Is this still "best practice" with Django-rest-framework? Wouldn't it be better to maintain … -
Read-only file system error while uploading image/files in django site in Vercel hosting
I have deployed my django site in vercel(using free hosting plan). Now while I am trying to create a model object (which has image/file field) from admin panel, is not saving. Instead of this it is showing that OSError at /admin/portfolio/biodata/add/ [Errno 30] Read-only file system: '/var/task/media' I think media folder is saved in /var/task/media this directory and this directory doesn't have any permission to write it. Here is my models.py: class Biodata(models.Model): name = models.CharField(max_length=100) profile_pic = models.ImageField(upload_to='img/profile_pic') about_me = models.TextField() cv_file = models.FileField(upload_to='files') created_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) .... .... def __str__(self): return self.name Now, can anyone tell me that how can I override the permission or solve this issue so that I can upload images or files from admin panel. Thanks in advance. -
Docker Container Build integrating Vite, React, Django & Postgres
I am trying to integrate Vite, Django, React and eventually DRF within Docker containers. However, I've been at it for a while, but everything I've tried has become a tangled web of frustration, so I'd be greatly indebted to anyone willing to provide some advice. I got the containers up and running with Django and Postgres with no issues. I then added Vite, and it seemed to be working correctly as well. However, once adding React and the rest of the "static files", whenever I build the container I face the following issues: First, the build fails to run unless I comment out the code in main.js (see below). When I comment out the code in main.js, the build completes, but when I visit the server, index.html loads (without any content), and I get a 404 - Not Found: /main.js in my Docker logs each time. In one iteration, I changed the <script type="module" src="main.js"></script> in index.html to src="frontend/main.js and I stopped getting the 404 error, and the <text>hello,world</text> element was displayed correctly. However, every successive container build fails with: Rollup failed to resolve import "frontend/main.js" from "/frontend/index.html". I'd include the full error, but there's enough code here already... File … -
ModelNotFoundError: No module named 'guardian.shortcuts'
I am trying to run a Django project, I tried to import assign_perm and remove_perm from guardian.shortcuts (code listed here: from guardian.shortcuts import assign_perm, remove_perm). and got an error: ModuleNotFoundError: No module named 'guardian.shortcuts' I am using python3.8.9 and django2.0.7. I have already tried install guardian(0.2.2) and Django-guardian(2.4.0). Please help me to figure it out. THX! -
How can i add a searchable drop down list/filter of cities?
I created a map using Folium in Python to visualize some geospatial data. However, I want to add a search bar with a drop-down list of cities that I want to manually write. This search bar should allow users to search for a specific city and, upon selection, the map should automatically pan to that city's location. How can I achieve this functionality using Folium? **index.html** <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous"> <title>HomePage</title> </head> <body> <!--- NAVBAR --> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Map App</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="{% url 'index' %}">Map <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> </ul> <form class="form-inline my-2 my-lg-0" method="post"> {% csrf_token %} {{form}} <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <!---END NAVBAR--> <div class="container"> <div class="row mt-5"> <div class="col-md-12 offset-md-0"> {{m | safe }} </div> </div> </div> <!-- Optional JavaScript; choose one of the two! --> <!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) --> <script … -
Django View - How to Efficiently Filter Combined Querysets from Multiple Models?
I have a Django view that combines and sorts querysets from three different models (Event, Subject, and Article) to create a feed. I'm using the sorted function along with chain to merge the querysets and sort them based on the 'created_at' attribute. The feed is then returned as a list. However, I'm facing challenges when it comes to filtering the feed based on user-provided search and author parameters. Since the feed is in list form, I can't directly use the filter method from the Django QuerySet. class FeedView(View): form_class = YourFormClass template_name = 'your_template.html' def get_queryset(self): """ Get the combined and sorted queryset from events, subjects, and articles. """ events = Event.objects.all() subjects = Subject.objects.all() articles = Article.objects.all() feed = sorted( chain(articles, subjects, events), key=attrgetter('created_at'), reverse=True, ) return feed def filter_queryset(self, queryset): form = self.form_class(self.request.GET) if form.is_valid(): data = form.cleaned_data search = data.get('search') if search: queryset = [item for item in queryset if search in getattr(item, 'name', '')] author = data.get('author') if author: queryset = [item for item in queryset if author in getattr(item, 'created_by__username', '')] return queryset def get(self, request, *args, **kwargs): queryset = self.get_queryset() queryset = self.filter_queryset(queryset) context = { 'object_list': queryset, } return render(request, self.template_name, context) -
Submenu not displaying properly when i fectch data from database in Django
Good all I wanted to create a dynamic menu with submenu populating the menus from database. I created two tables mainmenu which related to submenu. The mainmenu gets populated and is didplayed properly but the submenu is populated but does not dropdown properly, the submenu stays ontop of each other. However if I manually code both mainmenu and submenu both work far. What am I doing wrong? Thanks for your time. What I Wanted What I am Getting My Code - Django Template <div class="collapse navbar-collapse sub-menu-bar" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> {% for mainmenu in mainmenu %} <li class="nav-item"> <a href="{{ mainmenu.menulink }}">{{ mainmenu.name }}</a> {% for submenu in mainmenu.submenu.all %} <ul class="sub-menu"> <div> <a href="{{ submenu.menulink }}">{{ submenu.name }}</a> </div> </ul> {% endfor%} </li> {% endfor %} </ul> </div> My Custom Context Processor from setup.models import Setup, Mainmenu, Submenu def setup(request): setup = Setup.objects.first() return {'organisation': setup} def mainmenu(request): mainmenu = Mainmenu.objects.order_by("order").filter(menutype="main") return {'mainmenu': mainmenu} def submenu(request): submenu = Submenu.objects.order_by("order").filter(menutype="submenu") return {'submenu': submenu}` **My Database Table** class Mainmenu(models.Model): name = models.CharField(_("Menu Name"), max_length=256, blank=True, null=True, unique=False) menulink = models.CharField(_("Menu Link"), max_length=512, blank=True, null=True, help_text="Enter menu link like this, <code>https://uidc.com.ng/page/display/about-us/</code>") order = models.CharField(_("Menu Order"), max_length=512, blank=True, null=True) is_active = models.CharField(_("Is … -
how do i fix the look of the pages
Error Hi Everyone, I published my django project with ubuntu 22.04 and apache2, but it looks like the picture, I tried many ways for the solution but it didn't work, what do you think might be the reason, thanks in advance it should look like it's not like this