Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to handle concurrency of bookmark system in django?
I tried to implement bookmark system for product, when users click bookmark button, it will be recorded in his bookmark table, and update bookmark count field in Product Model. However I faced DB Lock when there is too many request at the same time. Also, I realized that when users add or delete bookmark at the same time, there will be concurency issues like, users can not read Product Information or Bookmark count or DB Lock.. How to handle concurrency in my situation? I know the exclusive lock but it will lower the performance.. please help me.. here are my codes class Bookmark(models.Model): _id = models.AutoField(primary_key=True, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='bookmark_user') def __str__(self): return str(self.user) class BookmarkItems(models.Model): _id = models.AutoField(primary_key=True, editable=False) user = models.CharField(max_length=255, null=True, blank=True) image = models.CharField(max_length=255, null=True, blank=True) bookmark = models.ForeignKey(Bookmark, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) def image_preview(self): if self.image: return mark_safe('<img src="{0}" width="75" height="75" />'.format(self.image)) else: return '(No image)' def __str__(self): return str(self.product) @api_view(['POST']) @permission_classes([IsAuthenticated]) def addBookmark(request): user = request.user user_id = request.data['user'] product_id = request.data['product_id'] image = request.data['image'] product = Product.objects.get(_id=product_id) with transaction.atomic(): bookmark = Bookmark.objects.get_or_create(user=user) Product.objects.filter(_id=product_id).update( bookmark_count = F('bookmark_count') + 1 ) BookmarkItems.objects.create( user = user_id, image = image, bookmark=bookmark[0], … -
PyCharm - Auto-reloading Django dev server after template changes
How to make my PyCharm to reload Django dev server after i make changes in templates? It reloads on save on every other changes but not for template changes. server is starting by docker compose up We are using Django 3.2.16 entrypoint.sh: exec gunicorn app.wsgi:application --config gunicorn.py --reload settings.py [...] TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "app.context_processors.get_version", "app.context_processors.get_env", ] }, } ] [...] -
Django static files are not found inside docker container
I am building a Django app with Docker. I run the command collectstatic in my entrypoint when database is ready. When I check my container, the /static/ folder is empty. Thus, Nginx cannot load the static files. # settings.py STATIC_URL = '/static/' STATIC_ROOT = '/static/' Here is my docker-compose file version: "3.9" services: db: image: postgis/postgis:14-3.3 container_name: db volumes: - ./data/db:/var/lib/postgresql/data env_file: - prod.env backend: container_name: backend build: dockerfile: ./django/Dockerfile command: gunicorn api.wsgi:application --bind 0.0.0.0:8000 volumes: - static:/usr/src/app/static ports: - "8000:8000" env_file: - prod.env depends_on: - db nginx: container_name: nginx build: dockerfile: ./nginx/Dockerfile volumes: - static:/usr/src/app/static ports: - "80:80" depends_on: - backend restart: always redis: container_name: redis restart: unless-stopped image: redis:alpine expose: - 6379 worker: container_name: worker build: dockerfile: ./django/Dockerfile command: celery -A api worker -l INFO volumes: - static:/usr/src/app/static env_file: - prod.env depends_on: - db - backend - redis volumes: static: My Nginx configuration: upstream api { server backend:8000; } server { listen 80; location / { proxy_pass http://api; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static/ { alias /usr/src/app/static/; } } backend Dockerfile: # syntax=docker/dockerfile:1 FROM python:3 WORKDIR /usr/src/app RUN apt-get update RUN apt-get install -y libgdal-dev gdal-bin netcat ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 COPY /django/requirements.txt … -
I want the number of unread messages to be displayed next to the menu in django admin panel
i need show number unread messages to be displayed next to the menu in django admin panel or show new user added site like this -
boto3 list items of s3 bucket and give path
I need to list all the items in my media/uploads/ folder on my s3 bucket. I've tried several answers from similar questions but was unable to implement the code snippets. I'm confused how to set up the boto3 connection and so far did not get a list. I work with django. In the end I need a list of the latest items. But getting a list of all the items in that folder would already help a lot. Here is my storage system: settings.py STATIC_URL = "static/" STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" AWS_STORAGE_BUCKET_NAME = "feedingcycle" AWS_S3_REGION_NAME = "eu-central-1" AWS_ACCESS_KEY_ID = "xxxx" AWS_SECRET_ACCESS_KEY = "xxxx" AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" import boto3 bucket_name = AWS_STORAGE_BUCKET_NAME def keys(bucket_name, prefix='/', delimiter='/'): prefix = prefix.lstrip(delimiter) bucket = boto3.resource('s3').Bucket(bucket_name) return (_.key for _ in bucket.objects.filter(Prefix=prefix)), print(keys) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" MEDIAFILES_FOLDER = "media" DEFAULT_FILE_STORAGE = "custom_storages.MediaFileStorage" The def keys is not working in there. I also don't get any error messages... Can I set up the whole thing also in my settings or do I have to make a new .py or model for that? Best wishes, Amber -
expected token 'end of statement block', got '='
I am trying to assign value to a dictionary in Jinja2 and its not working properly and showing error. expected token 'end of statement block', got '=' My Code: {% set sequence = ['a1', 'b1']%} {% set dic = {} %} {% for filter in search_result.filters %} {% for seq_key in sequence %} {% if seq_key == filter.key %} {# here i wish to create a dictionary where key= seq_key and value = filter_object#} {% do dic[seq_key]=filter %} {% endif %} {% endfor %} {% endfor %} -
Filter nested serializer model field (exclude particular field)
I am new to Django and I am trying to exclude a model field in nested serializer. modals.py class Blog(models.Model): title = models.CharField(max_length=30) description = models.CharField(max_length=30) class Comment(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE, related_name="comment") comment_bdy = models.CharField(max_length=30) completed = models.BooleanField(default=False) serializers.py class BlogCommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = ("id", "comment_body") class BlogSerializer(serializers.ModelSerializer): comment = BlogCommentSerializer(many=True) class Meta: model = ("id", "title", "description", "comment",) I am trying to exclude comment which have completed=True . I have tried many times like :- class BlogCommentSerializer(serializers.ModelSerializer): def to_representation(self, data): data = data.filter(completed=False) return super(BlogCommentSerializer, self).to_representation(data) But It showing AttributeError: 'CommentReply' object has no attribute 'filter' then I tried using class BlogSerializer(serializers.ModelSerializer): def get_comment(self, instance): comment_instance = instance.comment_set.exclude(completed=True) return BlogSerializer(comment_instance , many=True).data It also didn't work. What I am trying to do I am trying to exclude comments which are completed=True Any help would be much Appreciated. -
How can I merge different Db Models into one?
I have an old Django Project, which I started when I was a beginner. So far it worked but, due to some code refactoring I would like to do, I would like to change the original database models. Basically, I originally made many different models, each one for a user type. old models: class CustomUser(AbstractUser): user_type_data = ( ('admin', 'Admin'), ('instructor', 'Instructor'), ('student', 'Student'), ('renter', 'Renter'), ) user_type = models.CharField( max_length=20, choices=user_type_data, default=1) class Admin(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField(null=True, blank=True) fiscal_code = models.CharField(max_length=50, null=True, blank=True) phone = models.CharField(max_length=50, null=True, blank=True) picture = models.ImageField( blank=True, null=True, default='default.png') address = models.CharField(max_length=100, blank=True, null=True) cap = models.CharField(max_length=10, blank=True, null=True) city = models.CharField(max_length=100, blank=True, null=True) province = models.CharField( max_length=100, choices=PROVINCE_CHOICES, blank=True, null=True) country = CountryField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) is_active = models.BooleanField(default=True) def __str__(self): return self.user.username class Meta: ordering = ['last_name'] class Instructor(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) date_of_birth = models.DateField(null=True, blank=True) fiscal_code = models.CharField(max_length=50, null=True, blank=True) phone = models.CharField(max_length=50, null=True, blank=True) picture = models.ImageField( blank=True, null=True, default='default.png') address = models.CharField(max_length=100, null=True, blank=True) cap = models.CharField(max_length=10, null=True, blank=True) city = models.CharField(max_length=100, null=True, blank=True) province = models.CharField( max_length=100, … -
How to upload a file on click of a button in Django?
I have a requirement to upload a zip file on click of an upload/save button. Then when the user clicks on run button the uploaded file should get processed. I have created a basic form and could write code for uploading a file on click of submit as shown in below if request.method=='POST': upload_request=UploadFile() upload_request.file=request.FILES['file_upload'] upload_request.save() Template: <form method="post" enctype="multipart/form-data"> {% csrf_token%} <input type="file" required name="file_upload" id="choose_upload_file" value="" accept=".zip,.rar,.7z,.gz,"></br> <input type="submit" class="btn btn-secondary btn-block" value="upload" id="file_upload1"> </form> But How to have a save functionality (File should be uploaded) before submitting the form? I am new to Django, Please give me some insights. -
how to create a qr-code an sone of one of the fields based on the other when creating an object?
I want to creato objects through admin-pannel Django, I enter a value for a parameter and I want a qr code to be generated based on this value, my code: class People(models.Model): name = models.CharField(max_length=500, unique=True) qr_code = models.ImageField(upload_to="img/qr_codes/", verbose_name="QR-code", null = True) def save(self, *args, **kwargs): qr = qrcode.QRCode(version=2, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=1) qr.add_data(self.name) qr.make(fit=True) qr.make_image().save(f'img/qr_codes/{self.name}.png' self.qr_code = self.name+'.png' super().save(*args, **kwargs) This code return error [Errno 2] No such file or directory: 'img/qr_codes/somename.png' Im trying to use signal @receive but it isn't help for me -
How to use "Prefetch()" with "filter()" to reduce `SELECT` queries to iterate 3 or more models?
I have Country, State and City models which are chained by foreign keys as shown below: class Country(models.Model): name = models.CharField(max_length=20) class State(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=20) class City(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) name = models.CharField(max_length=20) Then, when I iterate Country, State and City models with prefetch_related() and all() as shown below: # Here # Here for country_obj in Country.objects.prefetch_related("state_set__city_set").all(): for state_obj in country_obj.state_set.all(): # Here for city_obj in state_obj.city_set.all(): # Here print(country_obj, state_obj, city_obj) Then, 3 SELECT queries are run as shown below. *I use PostgreSQL and these below are the query logs of PostgreSQL and you can see this answer explaining how to enable and disable the query logs on PostgreSQL: But, when I iterate with filter() instead of all() as shown below: # Here for country_obj in Country.objects.prefetch_related("state_set__city_set").filter(): for state_obj in country_obj.state_set.filter(): # Here for city_obj in state_obj.city_set.filter(): # Here print(country_obj, state_obj, city_obj) Then, 8 SELECT queries are run as shown below instead of 3 SELECT queries: So, I use Prefetch() with filter() to reduce 8 SELECT queries to 3 SELECT queries as shown below: for obj in Country.objects.prefetch_related( Prefetch('state_set__city_set', # Here queryset=State.objects.filter(), to_attr='result' ), ).filter(): print(obj.result) But, the error below occurs: django.core.exceptions.FieldError: Cannot … -
Is it possible to user this code like the first one instead of second?
def create_new(request): if request.method == 'POST': form = ArticleForm(request.POST) form.id_author = request.user.id if form.is_valid(): form.save() return redirect('home') return render(request, 'main/create_new.html') def create_new(request): if request.method == 'POST': form = ArticleForm(request.POST) if form.is_valid(): article = form.save(commit=False) article.author = request.user article.save() return redirect('home') return render(request, 'main/create_new.html') Is it possible to change the 2nd code into the first code?? it shows some kind of error -
Django Admin: Prevent initial value from changing
I currently have: def formfield_for_dbfield(self, db_field, request, obj=None, **kwargs): if db_field.name == "username": initial_username = obj.username if obj else generate_patient_number() kwargs["initial"] = initial_username kwargs["disabled"] = True kwargs[ "help_text" ] = "<span style='color: red;'>Number might change. Please look at banner once saved</span>" return super().formfield_for_dbfield(db_field, request, **kwargs) However, once a new instance is created, the value that was displayed initially changes. Is there a way to prevent this? -
How to resolve "Exception while resolving variable 'name' in template 'unknown'." error thrown while logging API calls?
My Django logging config: def get_config(log_dir, level="INFO"): return { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': "[%(asctime)s] %(levelname)s [%(name)s: %(funcName)s: %(lineno)s] %(message)s", 'datefmt': "%Y-%m-%dT%H:%M:%S%z" }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'null': { 'level': level, 'class': 'logging.NullHandler', }, 'console': { 'level': level, 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'django_log_file': { 'level': level, 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(log_dir, 'django.log'), 'maxBytes': 16777216, # 16megabytes 'formatter': 'verbose' }, 'django_errors_file': { 'level': 'ERROR', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(log_dir, 'django.errors.log'), 'maxBytes': 16777216, # 16megabytes 'formatter': 'verbose' }, 'db_log_file': { 'level': level, 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(log_dir, 'dbs.log'), 'maxBytes': 16777216, # 16megabytes 'formatter': 'verbose' }, 'apps_log_file': { 'level': level, 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(log_dir, 'apps.log'), 'maxBytes': 16777216, # 16megabytes 'formatter': 'verbose' }, 'myapp_ui_log_file': { 'level': level, 'class': 'logging.handlers.TimedRotatingFileHandler', 'when': 'midnight', 'filename': os.path.join(log_dir, 'myapp_ui.log'), 'interval': 1, 'backupCount': 7, 'formatter': 'verbose', }, 'myapp_apis_log_file': { 'level': level, 'class': 'logging.handlers.TimedRotatingFileHandler', 'when': 'midnight', 'filename': os.path.join(log_dir, 'myapp_apis.log'), 'interval': 1, 'backupCount': 7, 'formatter': 'verbose', } }, 'loggers': { 'django': { 'handlers': ['console', 'django_log_file', 'django_errors_file'], 'level': level, 'propagate': False, }, 'django.db.backends': { 'handlers': ['console', 'db_log_file'], 'level': level, 'propagate': False, }, '': { 'handlers': ['console', 'apps_log_file'], 'level': level, 'propagate': True, }, 'myapp_ui': { 'handlers': ['console', 'myapp_ui_log_file'], 'level': level, 'propagate': True, }, 'api1': { 'handlers': ['console', … -
Django Database transaction rollback in Loop
User may import a excel and I want to check if the data are correct. # Excel Data | id | item | qty | |:---- |:------:| -----:| | 1 | item A | 10 | | 2 | item B | 20 | | 3 | item C | 30 | | 4 | item D | 40 | <-- For example, Not enough qty to minus (only have 1) | 5 | item E | 50 | # Database | id | item | qty | |:---- |:------:| -----:| | 1 | item A | 100 | | 2 | item B | 200 | | 3 | item C | 300 | | 4 | item D | 1 | <-- For example, Not enough qty to minus (Need 40) | 5 | item E | 500 | I need to check the Database is that item has qty to minus, if yes then save the changes, if not, then rollback all changed data in this excel data (rollback to before import this excel) and return errors details to user. def myFunction(self, request): try: error_details = [] with transaction.atomic(): for data in excal_data: result = checkIfVerify(data) # … -
I keep getting this "OperationalError at / (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)")" after django deploy
I keep getting this "OperationalError at / (2002, "Can't connect to local server through socket '/run/mysqld/mysqld.sock' (2)")". I only turned DEBUG to True since to see what the error is and since I'm only the one currently accessing it. This is my first deployment of a django app. I've tried checking for the socket path, I can't find any folder called run. I think mysqld is in C:/Program Files/MySQL/MySQL Server 8.0/bin but when i tried setting C:\Program Files/MySQL/MySQL Server 8.0/bin/mysqld.mock it as my socket it didn't work either. I'd really appreciate the help -
How to use Exception in python?
I wrote code below. def get(self, request): ... try: ... ... food = Food.objects.get(food_id="red") if food: data = { "name" : food.name, } res.append(data) return JsonResponse({"success": res}, status=200) except Exception as e: return JsonResponse({"failed": e}, status=403) My intention is, I would like to go to exception and get 403 if there is no food. However, in this case, if there is no 'food' data, a 500 error (DoesNotExist) occurs. Why do I get this error? Am I misunderstanding the concept of exception? -
Django returns session id but doesn't authenticate user
I have the following code that sends requests to check JWT token, then authorize user and return authorized session with Access token, Refresh Token and Session ID. @csrf_exempt def new_login_view(request, *args, **kwargs): def convert_data(req): data = { "email": req.data['username'], "password": req.data['password'], } try: data["language"] = request.LANGUAGE_CODE except: data["language"] = request.POST.get('language', 'en') return data if request.user.is_authenticated and not request.META.get('HTTP_X_AVOID_COOKIES'): return HttpResponseRedirect(request.GET.get(KEY_NEXT, '/')) if request.method == 'POST': request_data = convert_data(request) # request to Accounts API to check if user exists response = send_service_request(EnumAuthUrls.sign_in.value, json_data=request_data, original_response=True) if isinstance(response, dict): return JsonResponse(response) if response.status_code == 200: tok_ac = response.headers.get(HEADER_ACCESS_KEY) tok_ref = response.headers.get(HEADER_REFRESH_KEY) # checking JWT token user = ApiAuthenticationBackend().authenticate(request, tok_ac) # creates session data = login_session(request, response, user) data['user_id'] = request.user.id data['account_id'] = request.user.profile.account_id data['balance'] = request.user.balance if request.META.get('HTTP_X_AVOID_COOKIES'): return JsonResponse(data) response = AuthResponse( data=data, ssid=request.session.session_key, access_token=tok_ac, refresh_token=tok_ref, ) return response else: return ErrorApiResponse(response.json()) service = urllib.parse.quote_plus(request.build_absolute_uri()) return HttpResponseRedirect(settings.ACCOUNTS_URL + f'login/?service={service}') Here's the code of login_session fucntion: def login_session(request: HttpRequest, response: HttpResponse, user): request.user = user request.session.create() base_data = response.json().get(KEY_DATA) return request.user.serialize(request, base_data, token=True) And here's the class AuthResponse that is eventually based on HttpResponse: class AuthResponse(SuccessResponse): def __init__(self, data={}, ssid='', access_token: str = '', refresh_token: str = '', **kwargs): super().__init__(data, **kwargs) if ssid: … -
Copy content from an html tag in a file to a tag in another html file
all in peace? In Django, I need the content of an HTML tag to appear in another template. Using the code JS: <script> var source = document.getElementById("teste").innerHTML; document.getElementById("texto").innerHTML = source; </script> <div id="teste">context</div> <div id="texto"></div> It even works in the same template, but if the destination tag is in another template, it doesn't work. Any idea? -
How to filter some words in a queryset
I have a variable, which contains stock symbols. I need to split each symbol, to compute it independently. print(Symbols_Splitted) #returns this ["'['AAPL", 'TSLA', "MSFT']'"] I need something to filter the relevant words, the pattern is always the same. I tried this, which works but I find out an issue. Some symbols have special characters in them like "EURUSD=X", and this code remove the "=" which makes it not valid. def convertor(s): perfect = re.sub('[^a-zA-Z]+', '', s) return perfect all = list(map(convertor, Symbols_Splitted)) So, by taking the first example I need something like this: Some_function(Symbols_Splitted) Symbols_Splitted[0] > AAPL Symbols_Splitted[1] > MSFT Symbols_Splitted[2] > TSLA -
I have a problem importing openai in Django for web application purposes
My python version is able to run open ai on its own, but when I tried to integrate it with Django I ran into the following issue: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 1031, in _bootstrap_inner self.run() ^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/threading.py", line 968, in run self._target(*self._args, **self._kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/commands/runserver.py", line 134, in inner_run self.check(display_num_errors=True) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( ^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() ^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: ^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/urls/resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) ^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) ^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/urls/resolvers.py", line 708, in urlconf_module return import_module(self.urlconf_name) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1206, in _gcd_import File "<frozen importlib._bootstrap>", line 1178, in _find_and_load File "<frozen importlib._bootstrap>", line 1149, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 690, in _load_unlocked … -
setting up and processing 2 modelforms with the same FormView class
I am trying to use a single FormView class to render and process two related but different ModelForms. One of the forms has FileInput as one of its fields and it is not submitting properly when I click the respective button. views.py class MyView(LoginRequiredMixin, FormView): template_name = "tmp.html" http_method_names = ["get", "post"] login_url = "/to/login" form_class = AForm success_url = reverse_lazy("profile") def get_context_data(self, **kwargs): context = super(MyView, self).get_context_data(**kwargs) prf = ModelA.objects.get(id=self.request.user.id) context["form_a"] = AForm(instance=prf) context["form_b"] = BForm(instance=None) return context def post(self, request, *args, **kwargs): if "submit_a" in request.POST: self.form_class = AForm if "submit_b" in request.POST: self.form_class = BForm return super().post(request, *args, **kwargs) def form_valid(self, form): if self.form_class == AForm: form.save() elif self.form_class == BForm: form.save() return super().form_valid(form) The related forms.py for ModelA looks something like this: class AForm(ModelForm): img_field = ImageField(widget=FileInput) Two issues I'm currently having: When the form loads and the user clicks the submit button with previous data, I'm getting <ul class="errorlist"><li>img_field<ul class="errorlist"><li>This field is required.</li></ul></li></ul> when I check form.errors. When the user selects an image to upload and clicks submit (submit_a), I'm getting IntegrityError on the id (user id) column which is returning null. I assume that since I am sending a specific user instance to the … -
Django, How to clear the previous data model thoroughly?
I'm viewing my admin site, but in the Add Groups page, I can still see the available permissions that I have deleted before. and in my models.py I haven't configured any of these table yet. Does this mean I didn't clear my database thoroughly? Is there any way to delete all of these, just leave the permissions I have in this list? Thank you! -
get a specific variable from a queryset
I'm trying to get a specific part of the cd output, but my code is not working. I'm trying to define a new variable, with only the object 'symbols' from the Queryset output. if cmd_exec == '/wanalysis': get_Memory = Memory.objects.filter(user=current_user).values() cd = get_Memory.all() X = cd['{id}'] print(X) This is the output for print(cd) <QuerySet [{'id': 183, 'user_id': 1, 'raw_message': '/setworkspace AAPL TSLA MSFT 12/12/2018 12/12/2022', 'date1': '2018-12-12', 'date2': '2022-12-12', 'symbols': "['AAPL', 'TSLA', 'MSFT']"}]> I would like to define a variable X, with the 'symbols' output from the QuerySet. So something like: X = cd['symbols'] -
Python/Django -> Gunicorn error: ModuleNotFoundError: No module named '<project directory>'
I'm trying to deploy a django application with Gunicorn and Nginx on Ubuntu server, but I'm getting this "ModuleNotFoundError". Can anyone help me out with this, please? The files gunicorn_myproject.socket [Unit] Description=myproject socket [Socket] ListenStream=/run/gunicorn_myproject.sock [Install] WantedBy=sockets.target gunicorn_myproject.service [Unit] Description=myproject daemon Requires=gunicorn_myproject.socket After=network.target [Service] User=myuser Group=www-data WorkingDirectory=/home/myuser/github/myproject ExecStart=/home/myuser/github/venvs/myproject/bin/gunicorn \ --access-logfile - \ --workers 5 \ --bind unix:/run/gunicorn_myproject.sock \ /home/myuser/github/myproject/MyProject.wsgi:application [Install] WantedBy=multi-user.target The error log: When I run sudo systemctl start gunicorn.socket then sudo systemctl status gunicorn.socket: ● gunicorn_myproject.socket - myproject socket Loaded: loaded (/etc/systemd/system/gunicorn_myproject.socket; enabled; vendor preset: enabled) Active: active (listening) since Tue 2023-01-31 18:43:11 -03; 1s ago Triggers: ● gunicorn_myproject.service Listen: /run/gunicorn_myproject.sock (Stream) CGroup: /system.slice/gunicorn_myproject.socket Jan 31 18:43:11 cpro49739 systemd[1]: Listening on myproject socket. Nothing wrong yet, so then I run curl --unix-socket /run/gunicorn_myproject.sock localhost and get: curl: (56) Recv failure: Connection reset by peer Then I run sudo systemctl status gunicorn.service aaaand: ● gunicorn_myproject.service - myproject daemon Loaded: loaded (/etc/systemd/system/gunicorn_myproject.service; enabled; vendor preset: enabled) Active: failed (Result: exit-code) since Tue 2023-01-31 18:47:29 -03; 1min 33s ago TriggeredBy: ● gunicorn_myproject.socket Process: 2539537 ExecStart=/home/myuser/github/venvs/myproject/bin/gunicorn --access-logfile - --workers 5 --bind unix:/run/gunicorn_myproject.sock /home/myuser/github/myproject/MyProject.wsgi:application (code=exited, status=3) Main PID: 2539537 (code=exited, status=3) Jan 31 18:47:29 cpro49739 gunicorn[2539539]: ModuleNotFoundError: No module named '/home/myuser/github/myproject/MyProject' Jan 31 …