Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SQLAlchemy disconnecting from SQLite DB on Django site
On my site built with Django, I have a dashboard page that I need to display statistics about campaigns running on the site. When running the following code locally, the dashboard page loads correctly, but when running it on the live server served through Nginx and Gunicorn I run into an error. The dashboard view: def sysDashboard(request): template = loader.get_template('AccessReview/sysdashboard.html') context = {} disk_engine = create_engine('sqlite:///db.sqlite3') pio.renderers.default="svg" print(disk_engine.table_names()) sqlQueries.info(disk_engine.table_names()) df = pd.read_sql_query('SELECT emp.pid, COUNT(*) as `num_reviews` ' 'FROM AccessReview_review rev ' 'JOIN AccessReview_employee emp ON rev.manager_id=emp.id ' 'GROUP BY emp.pid ' 'ORDER BY -num_reviews ', disk_engine) print(df) fig = go.Figure( data=[go.Bar(x=df['pid'], y=df['num_reviews'])], layout_title_text='AccessReview/Reviews per Manager').update_layout( {'plot_bgcolor': 'rgba(102,78,98,0.5)', 'paper_bgcolor': 'rgba(102,78,98,0.5)', 'font_color': 'rgba(255,255,255,1)' }) overview_df = pd.read_sql_query('SELECT sys.name, ' 'COUNT(*) as `num_reviews`, ' 'COUNT(1) FILTER (WHERE reviewComplete=1) as `Completed`, ' 'COUNT(1) FILTER (WHERE reviewComplete=0) as `Incomplete` ' 'FROM AccessReview_review ' 'JOIN AccessReview_System sys ON system_id=sys.id ' 'GROUP BY sys.name ' 'ORDER BY -num_reviews', disk_engine) print(overview_df) overview_fig = go.Figure( data=[go.Bar (x=overview_df['name'], y=overview_df['num_reviews'])], layout_title_text='Campaign Overview').update_layout( {'plot_bgcolor': 'rgba(102,78,98,0.5)', 'paper_bgcolor': 'rgba(102,78,98,0.5)', 'font_color': 'rgba(255,255,255,1)' }, xaxis={'title':'System', 'fixedrange':True}, yaxis={'title':'Review Count', 'fixedrange':True}) context['overviewGraph'] = overview_fig.to_html() return HttpResponse(template.render(context, request)) Like I said, this works when running the server locally using py manage.py runserver but not when accessing the site through … -
modify django model field on serializer
i have a model definition Class Book(): name = textfield() edition = textfield() i want the the name of the book as "edition name" if there is a edition data on the book object. otherwith i want to return only the book. how can i acheive that? can i use a serializermethod on the book serializer as class BookSerializer( ): name = serializers.SerializerMethodField() def get_name(self,book): if book.edition: return f"{book.edition}{book.name}" return book.name -
how to call function in django template using conditionals
I have a model for Group: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) size = models.BooleanField(default=False) max_size = models.IntegerField(default=10) closed = models.BooleanField(default=False, blank=True) The idea is that Users can join groups (thus adding to the total joined for that Group) and leave groups. They do that through this view: def join_group(request, pk): id_user = request.user.id group = Group.objects.get(id=request.POST.get('group_id')) account = Account.objects.get(user_id=id_user) if group.joined.filter(id=request.user.id).exists(): group.joined.remove(request.user) account.joined_groups.remove(group) else: group.joined.add(request.user) account.joined_groups.add(group) return HttpResponseRedirect(reverse('group_detail', args=[str(pk)])) And template: {% if user.is_authenticated %} <form action="{% url 'join_group' group.pk %}" method="POST"> {% if group.closed == True %} <div>Sorry, this group is closed</div> {% else %} {% csrf_token %} {% if joined %} <button type="submit" name="group_id" value="{{group.id}}">LEAVE</button> {% else %} <button type="submit" name="group_id" value="{{group.id}}">JOIN</button> {% endif %} {% endif %} </form> {% endif %} Users joining and leaving groups works fine, the thing I'm trying to implement is when the total_joined == group.max_size a function would be called to close the group. Since, as of now the only way too close a Group is for the User who created it to go and update the Group to change closed=True. What I'm trying to do is call a function within … -
{'field': [ErrorDetail(string='This field is required.', code='required')] - DJANGO REST FRAMEWORK
I'm trying to parse the JSON data nad import it to the database through API. I think I almost got it but still getting this message: {'field': [ErrorDetail(string='This field is required.', code='required')] from my HttpResponse and I don't really know what to do with it. Here is my code: models.py from django.db import models` class Data(models.Model): name = models.CharField(max_length=255, blank=False) eid = models.DecimalField(max_digits=10, decimal_places=0, blank=False) data = models.TextField(max_length=800, blank=True) def __str__(self): return "ID: {} -- Name: {}".format(self.eid, self.name) serializers.py I honestly think that the problem is in the serializers but can't figure it out what to add here. from .models import Data from rest_framework import serializers class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ['name', 'eid', 'data'] class DetailSerializer(serializers.ModelSerializer): class Meta: model = Data fields = '__all__' views.py Here I must have 3 views. First for Import. Second for show basic data like name, id, etc. which are given from the JSON file I provide to import/ API. And third for full details of the data given from the JSON file. from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse, HttpResponse from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view, authentication_classes, permission_classes from rest_framework.exceptions import ParseError from … -
How to solve "field must be unique" in django?
I am creating an app with vue and django but struggle with getting information from serializer. my models look like this: models.py from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) class Order(models.Model): name = models.CharField(max_length=255) posted_by = models.ForeignKey(Profile, on_delete=models.CASCADE) class Offer(models.Model): order_related = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='offers') author = models.ForeignKey(Profile, on_delete=models.CASCADE) serializers.py: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ("user",) class OfferSerializer(serializers.ModelSerializer): author = ProfileSerializer() class Meta: model = Offer fields = ("id", "order_related", "author", ) class OrderSerializer(serializers.ModelSerializer): posted_by = ProfileSerializer() class Meta: model = Order fields = ("id", "posted_by", "name") views.py: class OfferView(ListModelMixin, GenericAPIView, CreateModelMixin): queryset = Offer.objects.all() serializer_class = OfferSerializer def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) when i send info to this view: const formData = { order_related: this.$route.params.order_id, author: {user: localStorage.getItem("user")}, } axios .post("api/v1/offers/", formData) i get error: {"user":["Values of field must be unique."]} Is there any way to override this? P.S. To write AbstactUser model etc. - not a way -
Django Pytest gives Kombu Connection refused[111] using rabbitmq and celery
Presently I am using pytest, django and rabbitmq-server with celery for background tasks I do notice however that when I run pytest without running the server on my local machine it causes a long exception thread notably showing E: Kombu Connection refused[111] I am running a test for save() model method which in turn triggers a background celery task I wish to ask if there is a way to start rabbitmq-server in pytest without actually starting it on the local machine so my testcases will passes This also affects my github CI/CD since I have no idea on how to run the rabbitmq image service in github-actions.yml file Your help is appreciated If you wish you can peruse the logs below self = <promise: 0x7fd0819d9d80> def __call__(self): try: > return self.__value__ E AttributeError: 'ChannelPromise' object has no attribute '__value__' ../../../.local/lib/python3.10/site-packages/kombu/utils/functional.py:30: AttributeError During handling of the above exception, another exception occurred: self = <Connection: amqp://guest:**@127.0.0.1:5672// at 0x7fd082053010> ConnectionError = <class 'kombu.exceptions.OperationalError'> ChannelError = <class 'kombu.exceptions.OperationalError'> @contextmanager def _reraise_as_library_errors( self, ConnectionError=exceptions.OperationalError, ChannelError=exceptions.OperationalError): try: > yield ../../../.local/lib/python3.10/site-packages/kombu/connection.py:446: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
Specify an exception class to catch or reraise the exception - how to catch exceptions in proper way?
In Sonar lint I see this message: Specify an exception class to catch or reraise the exception My class: class GetCountryByIPApiView(APIView): def get(self, request, *args, **kwargs): ip_address = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get( 'REMOTE_ADDR', '')).split(',')[-1].strip() try: ip_country = DbIpCity.get(ip_address, api_key='free').country except: ip_country = 'US' return Response({'country_code': ip_country.lower()}, status=status.HTTP_200_OK) DbIpCity class: https://github.com/tomas-net/ip2geotools/blob/master/ip2geotools/databases/noncommercial.py#L25 How should I improve this? -
Tips to better manage the creation of a non-nullable object through signals
I find myself in this situation: In models: class Client(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # other... signals.py: @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Client.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.client.save() There are specific fields of the Client class that cannot be null and therefore I get errors like: NOT NULL constraint failed: accounts_client.dob What is the best solution in this case? -
How to customize the in_active user error message for rest_framework_simplejwt in Django
I have set my multiple user model in Django rest framework and I am using dj_rest_auth, allauth and djangosimplejwt for my user Authentication and Authorisation workflow my serialisers.py look like this class LoginSerializer(Serializer): email = EmailField(required=False, allow_blank=True) password = CharField(style={'input_type': 'password'}) class Meta: model = Users fields = ['email', 'password'] extra_kwargs = { 'password': {'write_only': True}, 'style': {'input_type': 'password'}, } def authenticate(self, **kwargs): return authenticate(self.context['request'], **kwargs) def _validate_email(self, email, password): if email and password: user = self.authenticate(email=email, password=password) else: msg = {'error': _('Did you forget to include an email or password?')} raise ValidationError(msg) return user def get_auth_user_using_allauth(self, email, password): from allauth.account import app_settings # Authentication through email if ( app_settings.AUTHENTICATION_METHOD == app_settings.AuthenticationMethod.EMAIL ): return self._validate_email(email, password) def get_auth_user(self, email, password): """ Retrieve the auth user from given POST payload by using either `allauth` auth scheme or bare Django auth scheme. Returns the authenticated user instance if credentials are correct, else `None` will be returned """ if 'allauth' in settings.INSTALLED_APPS: # When `is_active` of a user is set to False, allauth tries to return template html # which does not exist. This is the solution for it. See issue #264. try: return self.get_auth_user_using_allauth(email, password) except url_exceptions.NoReverseMatch: msg = {'error': _('Unable to … -
How to access a website deployed on heroku from an iframe?
I created a website in Django that I deployed on heroku. It contains the following line in its settings.py file: ALLOWED_HOSTS = ['*'] This means that it allows connection with any domain name. But when I try to access a site from an iframe on an html page from my localhost, I get the following error when loading my webpage: gkwhelps.herokuapp.com refused the connection. here is the code of my iframe: <Iframe src="https://gkwhelps.herokuapp.com" width="450px" height="450px" /> I don't know why this happens because I authorized access to all hosts before deploying on heroku, I don't know if heroku has a policy about this which conditions the access to other hosts or the error comes from elsewhere. Thanks ! -
How to add new row into a table in Django Python?
The workflow of the current work is user add forms and has a selection of visit status containing approved and canceled. For example , user select visit status as approved and fill in other fields and save the form. A new row will be added in the table ClinicVisitStatusRecord() and ClinicVisitStatusHistory.Then when the user edit the form and want to change the visit status to canceled, it does not add a new row in the table ClinicVisitStatusRecord() and ClinicVisitStatusHistory and it also does not overwrite the data. Is there any to create a new row again? serializers.py class ClinicVisitSerializer(serializers.ModelSerializer): clinic_detail = ClinicSerializer(read_only=True, source='clinic') staff_relationship_detail = StaffRelationshipSerializer(read_only=True, source='staff_relationship') staff_detail = StaffSerializer(read_only=True, source='staff') person_visit_name = serializers.CharField(max_length=100, min_length=None, allow_blank=True, help_text='The name of person visiting the clinic') bill_amount = serializers.DecimalField(max_digits=None, decimal_places=2, help_text='The clinic visit cost') class Meta: model = ClinicVisit exclude = clinicvisit_exclude extra_kwargs = { "staff_relationship": {"required": True}, "visit_type": {"required": True}, "visit_status": {"required": True}, } def create(self, validated_data): obj = ClinicVisit.objects.create(**validated_data) if obj.visit_status == "canceled" : obj.create_new_clinic_visit_statuses_history(action_by=obj.staff) obj.create_visit_status_history(action_by=obj.staff) print('OK 1') if obj.visit_status == 'approved': obj.create_new_clinic_visit_statuses_history(action_by=obj.staff) obj.create_visit_status_history(action_by=obj.staff) print('OK 2') models.py class ClinicVisit(models.Model): uuid = models.UUIDField(default=uuid.uuid4, editable=False) staff = models.ForeignKey(Staff, on_delete=models.CASCADE) staff_relationship = models.ForeignKey( StaffRelationship, on_delete=models.SET_NULL, blank=True, null=True,) clinic = models.ForeignKey( Clinic, on_delete=models.SET_NULL, blank=True, null=True,) … -
Django ManyToMany with quantity
I'm having a bit of a problem trying to model something in Django that I've conceptualized. I know that it is a many to many relationship... however it is sort of self referential and has a quantity involved. I imagine this requires a bridge model of some sort, which I have, but now how do I edit them in the admin page? What I have is a Component class. For example, a 'screw' is a component, and it requires no further components to create it. But so is a 'housing', which requires 4 screws to hold it together. That housing could then go into a manifold and the manifold could go into a vehicle and so forth. Each thing could potentially be a component of another thing if that makes sense. I've put all of the screws and bolts and such into the database through the admin edit page. But now I want to start putting in more complex assemblies. I could just create an Assembly class which has a list of one or more components. But I'm still left with the problem that this assembly could go into a larger assembly zero or more times. How do I represent … -
Django submit two forms within one view
I'm trying to submit two forms within one view. First, a user shares a URL through the first form. My program then renders some graphs and will ask the user at the end of the page to fill out a form and submit it. Here's how I'm trying to solve it: views.py: if request == "POST": if 'first-input-name' in request.POST: # or in request.POST.get('name') # do something elseif 'second-input-name' in request.POST: # or in request.POST.get('name') # do something else template: <input type="submit" name="first-input-name"/> <input type="submit" name="second-input-name"/> This is the approach I found in answers to similar questions. However, in my requests.POST I don't find the name of my input, and therefore I don't get the expected behavior. Any ideas on how to solve this? -
How to merge different models in django
I have the following initial situation: My application processes data stored in the django db and some external data accessible through an REST API. What would be the best "django style" approach to Query data from db Retrieve data from api Merge data to a "proxy" model return that proxy model to a view Same for create, update, delete. Thanks for your help! -
Django import-export by user/role
I'm using Django import/export package and I want to give permissions by role or user name for import/export in my admin. for example, admin.py: @admin.register(App) class appAdmin(ImportExportModelAdmin): limited_fiels = ("id", "app_name", "app_family", "app_category", "sv_available") list_display = ["id", "app_name", "app_family", "update_user", "updated_at"] list_filter = ("app_name", "app_category", "id") search_fields = ["app_name", "app_family", "id", "app_category"] TNX -
[Python][Pyinstaller][Django][threading] Multithread don't work in exe created by pyinstaller
Problem: After changing to exe Thread not start. When i run in pycharm everything work properly. App info and sample code: My app mix django with custom app. Django start by command: .\myapp.exe runserver localhost:40218 --noreload. import os import threading import django from django.core.management.commands.runserver import Command as runserver os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'rest_api.settings.base') django.setup() runserver.default_port = "40218" from app.processes import start_processing # noqa: E402 from app.threads_configuration import multiple_threads_creator_wrapper # noqa: E402 from manage import main # noqa: E402 if __name__ == '__main__': try: ctx = ctx_manager() threading.Thread(target=multiple_threads_creator_wrapper, args=(start_processing,)).start() main() except Exception as e: print(f'Application closed due to error: {str(e)}') -
Got ModuleNotFoundError error while running app from docker-compose. How can i solve this?
I got following error while running from docker-compose but it works fine when I run docker run . Can some body help me to debug this. Error: File "/home/desktop/.local/bin/docker-compose", line 5, in <module> from compose.cli.main import main File "/usr/lib/python3.10/site-packages/compose/cli/main.py", line 19, in <module> from ..config import ConfigurationError File "/usr/lib/python3.10/site-packages/compose/config/__init__.py", line 3, in <module> from .config import ConfigurationError File "/usr/lib/python3.10/site-packages/compose/config/config.py", line 48, in <module> from .validation import match_named_volumes File "/usr/lib/python3.10/site-packages/compose/config/validation.py", line 8, in <module> from jsonschema import Draft4Validator File "/usr/lib/python3.10/site-packages/jsonschema/__init__.py", line 21, in <module> from jsonschema._types import TypeChecker File "/usr/lib/python3.10/site-packages/jsonschema/_types.py", line 3, in <module> from pyrsistent import pmap ModuleNotFoundError: No module named 'pyrsistent' My Dockerfile: FROM python:3.9-alpine ENV PYTHONUNBUFFERED=1 RUN apk update \ && apk add --no-cache --virtual .build-deps RUN pip install --upgrade pip ENV APP_DIR /home/myapp WORKDIR ${APP_DIR} ADD requirements.txt ${APP_DIR}/ RUN pip install -r ${APP_DIR}/requirements.txt COPY . . EXPOSE 8000 ENTRYPOINT sh -c "python manage.py runserver 0.0.0.0:8000" my docker compose file: version: "3.9" services: web: build: context: . volumes: - .:/home/myapp ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8000 container_name: django_myapp restart: always env_file: .env While I run docker-compose build I get above error. I have Tried adding pyrsistent in requirements.txt but error is still same. How to solve … -
Django get data in serializer from two steps away related table
I have the below models: class Campaign(Base): name = models.CharField(max_length=100, unique=True) display_name = models.CharField(max_length=100) class SubTopic(Base): name = models.CharField(max_length=100, unique=True) display_name = models.CharField(max_length=100) class CampaignSubTopicAssn(Base): campaign = models.ForeignKey(Campaign, related_name='subtopic_assn', on_delete=models.CASCADE) subtopic = models.ForeignKey(SubTopic, related_name='campaign_assn',on_delete=models.PROTECT) class Meta: unique_together = ('campaign', 'subtopic') class CampaignSubTopicAssnSerializer(serializers.ModelSerializer): class Meta: model = org_models.ContextualCampaignSubTopicAssn fields = ['subtopic'] In my campaign serializer I want to fetch all the subtopic_ids and their display_name as well: currently this serializer just gives the ids and not the name, basically the table is two steps away in relation. class CampaignSerializer(serializers.ModelSerializer): subtopic_assn = CampaignSubTopicAssnSerializer(many=True) -
Django Google News Sitemap
Does anyone know how to implement the google news sitemap standard on Django? https://developers.google.com/search/docs/advanced/sitemaps/news-sitemap I am struggling to find any mention of how its implemented with Django. Example of how it should look. <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9"> <url> <loc>http://www.example.org/business/article55.html</loc> <news:news> <news:publication> <news:name>The Example Times</news:name> <news:language>en</news:language> </news:publication> <news:publication_date>2008-12-23</news:publication_date> <news:title>Companies A, B in Merger Talks</news:title> </news:news> </url> </urlset> What I currently have looks very simple. <url> <loc>https://mynewsite.net/news/this-news-article/</loc> <lastmod>2022-04-04</lastmod> </url> <url> -
ModuleNotFoundError how to import my flie in django.view
I want to import my python files in django app import myfile dct = myfile.myfunc() def index(request): context = dct return render(request, 'myapp/index.html', context) >>>ModuleNotFoundError: No module named -
Django how to prevent patched method running when created in super class
I have a model with a post-save method that I don’t want to run in test: class MyModel(models.Model): def save(self, *args, **kwargs): super(MyModel, self).save(*args, **kwargs) self.post_save_method() def post_save_method(self): print("oh no!") return "real value" If I make a normal test everything works as I would expect. I can patch the method, and see that I get the mocked return value, and that the post_save_method does not run (nothing is printed from this method to the console): from django.test import TestCase from .models import MyModel from unittest.mock import patch class TestMakeObjectNormally(TestCase): @patch.object(MyModel, 'post_save_method') def test_something(self, post_save_mock): post_save_mock.return_value = "mocked value" my_model = MyModel.objects.create() print(my_model.post_save_method()) But the way the tests are set up is that the instance is created in a superclass. Following this gist I tried to patch at a class level: class BaseTest(TestCase): def setUp(self): self.my_model = MyModel.objects.create() @patch.object(MyModel, 'post_save_method') class TestMakeObjectInSuper(BaseTest): def setUp(self): super().setUp() def test_something(self, post_save_mock): post_save_mock.return_value = "mocked value" print(self.my_model.post_save_method()) This works in that the post_save_method return value is the mocked one, but unfortunately I can see that the method is running (“oh no!” is printed to the console). (I also tried patching both setUp() methods and the base class) Any advice appreciated! -
django mocking serializer __init__
I want in my test to mock the __init__ of a serializer as follow : serializer = MySerializer(data={'name':'yosi'}) serializer.data # will return {'name':'yosi'} and ignore default behavior, like requiring to call is_valid first I just want the serializer to store data as is, and not do the usual __init__ The method I want to test : MyDAO.py : from ..models import MyModel from ..serializers import MySerializer def getAll() -> list[dict]: entities = MyModel.objects.all() serializer = MySerializer(entities, many=True) return serializer.data I tried the following, with no success : def _mocked_seriailzer__init__(self, data, many): self.data = data @mock.patch('<PATH_TO_SERIALIZERS_FILE>.MySerializer.__init__', _mocked_seriailzer__init__) @mock.patch.object(MyDAO, 'MyModel') def test_getall(self, model): mockedData = ['mocked-data1', 'mocked-data2', 'mocked-data3'] model.objects.all.return_value = mockedData self.assertEqual(mockedData, MyDAO.getAll()) but it complains that the test is missing 1 required positional argument: 'many' def _mocked_seriailzer__init__(self, data, many): self.data = data @mock.patch.object(MyDAO, 'MySerializer.__init__', _mocked_seriailzer__init__) @mock.patch.object(MyDAO, 'MyModel') def test_getall(self, model): mockedData = ['mocked-data1', 'mocked-data2', 'mocked-data3'] model.objects.all.return_value = mockedData self.assertEqual(mockedData, MyDAO.getAll()) but it says that the MyDAO does not have the attribute 'CctSerializer.__init__' how to mock the serializer.init correctly? -
Python Fixtures:AttributeError: 'list' object has no attribute 'replace'
I am trying to load fixtures from a JSON file but get the above mentioned error when I run python3 manage.py loadfixtures /path/to/fixture.json. The fixture tries to model categories and their subcategories. Is this the most efficient way of loading default data on a database? My code and error logs are as shown below. Here are my models class SubCategory(BaseModel): description = models.TextField(null=True, blank=True) class Category(BaseModel): description = models.TextField(null=True, blank=True) sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE, related_name="category_subcategory") Here are my sample fixtures [{ "model": "accounts.category", "pk": 1, "fields": { "description": "Agricultural Businesses and cooperatives", "sub_category": [ { "model": "accounts.subcategory", "pk": 56, "description": "Piece Goods, Notions, and Other Dry Goods" }, { "model": "accounts.subcategory", "pk": 158, "description": "Florists" } ] } }] And here is the error log Traceback (most recent call last): File "/django-project/venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 2434, in to_python return uuid.UUID(**{input_form: value}) File "/usr/lib/python3.10/uuid.py", line 174, in __init__ hex = hex.replace('urn:', '').replace('uuid:', '') AttributeError: 'list' object has no attribute 'replace' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/django-project/venv/lib/python3.10/site-packages/django/core/serializers/python.py", line 134, in Deserializer value = base.deserialize_fk_value(field, field_value, using, handle_forward_references) File "/django-project/venv/lib/python3.10/site-packages/django/core/serializers/base.py", line 322, in deserialize_fk_value return model._meta.get_field(field_name).to_python(field_value) File "/django-project/venv/lib/python3.10/site-packages/django/db/models/fields/__init__.py", line 2436, in to_python raise exceptions.ValidationError( django.core.exceptions.ValidationError: … -
Write permission nginx gunicorn
In my django/python code I have the following lines: f = open(os.path.join(DIRECTORY, filname), 'w') f.write(filecontent) f.close() when I have DIRECTORY='/tmp/' it all works fine, the file.txt is saved with owner=root and group=www-data. However, when I want to save the file in a subdirectory of my django-project, for example DIRECTORY='/project/subfolder' the file doesn't appear, although I have that subfolder set to the same owner/group. I suspect that it is a permission problem with nginx or gunicorn. Any suggestions? I tried to solve my problem by just mounting the /tmp/ directory to the docker container where I use the file afterwards. But I ran into the problem, that files in the /tmp/ directory do not appear in docker, while as when I mount another folder like /project/subfolder/, these files do appear in docker. So either way, half works, but never both. -
Creating multiple Profiles instead of one In Django
When logging in, create a profile, But when logging out and then logging in with that same username, It again says to me to create a profile and creates two profiles instead of one. #For Cystomer Registration class CustomerRegistrationView(View): def get(self,request): form = CustomerRegistrationForm() return render(request,'mp/register.html',{'form':form}) def post(self,request): form = CustomerRegistrationForm(request.POST) if form.is_valid(): messages.success(request,'Congratulations Registerd Succesfuly ') form.save() success_url = reverse_lazy('profilecreate') return render(request,'mp/register.html',{'form':form}) #For Creating Profile class ProfileCreate(LoginRequiredMixin,CreateView):#ye hogia hamara upload wala model = Profile fields = ['user_name','user_ethnicity','SelectGender','user_job','user_age','mother_additionalinfo'] success_url = reverse_lazy('profile') def form_valid(self,form): form.instance.user = self.request.user success_url = reverse_lazy('profile') return super(ProfileCreate,self).form_valid(form) here are my URLs #for register path('register/',views.CustomerRegistrationView.as_view(),name= 'register'), #for CreateProfile path('profilecreate/',views.ProfileCreate.as_view(),name= 'profilecreate'), when User Created and I remove the loginrequiredmixin from profilecreateview. It give me an error of Page No Found With This Url:127.0.0.1:8000/accounts/login/?next=/profilecreate. It does not go to Profile Create View because it is not logged in but just Registered. And I want the User Go to Profilecreateview only one time. Later he can Update it. –