Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it bad to run a fake initial migration during deployment? (Django)
When deploying my Django project, I kept getting this error: W: psycopg2.errors.DuplicateTable: relation "materials_location" already exists W: The above exception was the direct cause of the following exception: --snip-- W: django.db.utils.ProgrammingError: relation "materials_location" already exists While the problem seems self-explanatory, this error first started appearing after I manually altered the database when I had to rename apps and move models around apps. ("materials_location" was one of the things I'd added.) I eventually found this solution: running python manage.py migrate --fake-initial during the deploy hook (instead of just python manage.py migrate). This allowed Django... ...to skip an app’s initial migration if all database tables with the names of all models created by all CreateModel operations in that migration already exist. Problem solved. The rest of the migration was applied correctly (which included the addition of fields to the existing models) and the project was deployed without any errors. Is there a scenario where this solution could backfire down the line? Like, what if I deploy to a new server and make a brand new database? Or if I reset or squash migrations? I feel like this is safe, but straying from python manage.py migrate makes me uneasy. -
My django is no longer working because of the algorithm version not specified
I'm practicing creating a RESTAPI for ML model deploymentFrom this site. By repeating the various processes such as data migration and testing. I feel like I'm duplicating things. I even had to change the owner and relaunch the codes. I see that new endpoints, MLagorithm, MLalgorithmstatus are created instead of the old ones being overwritten (which is what I expected) HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "name": "random forest", "description": "Random Forest with simple pre- and post-processing", "code": "class RandomForestClassifier:\n def __init__(self):\n path_to_artifacts = \"../../research/\"\n self.values_fill_missing = joblib.load(path_to_artifacts + \"train_mode.joblib\")\n self.encoders = joblib.load(path_to_artifacts + \"encoders.joblib\")\n self.model = joblib.load(path_to_artifacts + \"random_forest.joblib\")\n\n def preprocessing(self, input_data):\n # JSON to pandas DataFrame\n input_data = pd.DataFrame(input_data, index=[0])\n # fill missing values\n input_data.fillna(self.values_fill_missing)\n # convert categoricals\n for column in [\n \"workclass\",\n \"education\",\n \"marital-status\",\n \"occupation\",\n \"relationship\",\n \"race\",\n \"sex\",\n \"native-country\",\n ]:\n categorical_convert = self.encoders[column]\n input_data[column] = categorical_convert.transform(input_data[column])\n\n return input_data\n\n def predict(self, input_data):\n return self.model.predict_proba(input_data)\n\n def postprocessing(self, input_data):\n label = \"<=50K\"\n if input_data[1] > 0.5:\n label = \">50K\"\n return {\"probability\": input_data[1], \"label\": label, \"status\": \"OK\"}\n\n def compute_prediction(self, input_data):\n try:\n input_data = self.preprocessing(input_data)\n prediction = self.predict(input_data)[0] # only one sample\n prediction = self.postprocessing(prediction)\n except Exception as e:\n return {\"status\": \"Error\", \"message\": … -
Django Compressor: multiple errors when ran but working fine
I have installed django-compressor==2.4.1 on my Django==2.2.28 project. As on the documentation, I installed it by putting compressor in my INSTALLED_APPS and added 'compressor.finders.CompressorFinder' to my STATICFILES_FINDERS. by now I am just trying it and using it on my base.html on the following: {% compress css %} <link rel="stylesheet" type="text/css" href="{% static 'css/survey.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'css/Roboto.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/AdminLTE.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/jquery.dataTables.min.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'css/index.css' %}"/> {% endcompress %} And I enabled the following settings: # Django Compressor COMPRESS_ENABLED = True COMPRESS_OFFLINE = True COMPRESS_OFFLINE_TIMEOUT = 31536000 # 1 year in seconds but when I run manage.py compress the console is filled with errors, all about files that seem to be in the very same django-compressor folder. The compressed file gets made anyway and everything works fine. Here is the full output: https://pastebin.com/20kuHKLw Can anyone explain what is happening? -
Models aren't loaded yet wih django and celery
Hey i am using django and celery to run a app which seems to work fine all my tasks are picked up, but i cant seem to run the celery inspect command. I am using rabbitmq as my message broker which seems to work fine for sending and receiving tasks Django==3.2.19 celery==5.3.1 amqp==5.1.1 kombu==5.3.1 my celery.py looks like this, which has been copied mostly from the celery docs import os import celery from django import conf os.environ.setdefault(conf.ENVIRONMENT_VARIABLE, 'proj.settings') from django.conf import settings app = celery.Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) The error traceback that I am getting when running celery -A proj.celery inspect active not managed to find anything for models not being loaded, seems to be a lot of posts relating to apps not being loaded Traceback (most recent call last): File "/home/user/bin/celery", line 8, in <module> sys.exit(main()) File "/home/user/lib/python3.8/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/home/user/lib/python3.8/site-packages/celery/bin/celery.py", line 217, in main return celery(auto_envvar_prefix="CELERY") File "/home/user/lib/python3.8/site-packages/click/core.py", line 1157, in __call__ return self.main(*args, **kwargs) File "/home/user/lib/python3.8/site-packages/click/core.py", line 1078, in main rv = self.invoke(ctx) File "/home/user/lib/python3.8/site-packages/click/core.py", line 1688, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/user/lib/python3.8/site-packages/click/core.py", line 1434, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/user/lib/python3.8/site-packages/click/core.py", line 783, in invoke return __callback(*args, **kwargs) File "/home/user/lib/python3.8/site-packages/click/decorators.py", line … -
Saving objects related through many to many fields throwing field error
I have some models that are inter-related through various relations, including M2M relations. I have overridden create methods of 2 of the model's serializers so that I can create all the related objects through one post. But it keeps throwing the follwoing error :- { "permissions": { "ui_element": [ "Incorrect type. Expected pk value, received UIElement." ] }, "hospital": [ "Incorrect type. Expected pk value, received Hospital." ] } I can't for the life of me figure out how to solve this. Here's my models.py class StaffPermissions(TimeStampedModel): """ This table stores all the permissions that each staff has fields: - {ui_element}: foreign key to UIElement table - {create}: boolean field to store if the staff has create permission - {read}: boolean field to store if the staff has read permission - {update}: boolean field to store if the staff has update permission - {delete}: boolean field to store if the staff has delete permission """ ui_element = models.ForeignKey(UIElement, on_delete=models.CASCADE) create = models.BooleanField(default=False) read = models.BooleanField(default=False) update = models.BooleanField(default=False) delete = models.BooleanField(default=False) class HospitalDoctor(TimeStampedModel): """ This talbe stores all the information related to staff and their roles for a given hospital fields: - {hospital}: foreign key to Hospital table - {doctor}: … -
Django error: value must be either True or False
I'm currently having this error message on django: ["*** value must be either True or False."] It's really strange that I could not found where's the bug manager.py models.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, password, email, **extra_fields): if not username or not password or not email: raise ValueError("All values must be filled!") if not password: raise ValueError("Password could not be empty!") user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(username, password, **extra_fields) def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(username, password, **extra_fields) models.py import hashlib import uuid from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token import server.settings as settings from user.manager import UserManager STATUS_CHOICES = ( (0, "禁用"), (1, "启用"), ) class Users(AbstractUser): userid = models.AutoField(primary_key=True, verbose_name="用户ID", help_text="用户ID") username = models.CharField(max_length=150, unique=True, db_index=True, verbose_name="用户账号", help_text="用户名") email = models.EmailField(max_length=255, verbose_name="邮箱", null=True, blank=True, help_text="邮箱") avatar = models.CharField(max_length=255, verbose_name="头像", null=True, blank=True, help_text="头像", default="https://api.vvhan.com/api/qt?qq=771151240") VIP_CHOICES = ( (0, "普通用户"), (1, "VIP用户"), … -
Refactor or Relocation of data range validation in Views
im new to stack and dont know if its the best way to post, but im learning. I have a view in Django to validate dome data range fields that i have built with bootstrap, But im learning about managers, querysets and im trying to follow best practices. I feel that i can refactor this view, or shrink in size using forms and etc. Could you give me some tips? this views is large? can be refactored or relocated to other files, like forms? thanks in advance. https://github.com/paasxx/crypto-site/tree/sqlite_to_postgre/app_crypto def market(request, crypto): crypto_name = crypto crypto_model = getModelByName(crypto) sd = request.GET.get("startDate") ed = request.GET.get("endDate") min_date_table = crypto_model.crypto_objects.first_date().date max_date_table = crypto_model.crypto_objects.last_date().date crypto_data_all = crypto_model.crypto_objects.all_data() if sd == None and ed == None or sd == "" and ed == "": crypto_data = crypto_data_all context = { "currencies": currencies, "crypto": crypto_name, "crypto_data": crypto_data, "min_date_table": min_date_table, "max_date_table": max_date_table, } return render(request, "app_crypto/crypto_list.html", context) else: if datetime.strptime(ed, "%Y-%m-%d") < datetime.strptime(sd, "%Y-%m-%d"): messages.warning( request, "End Date must be greater than Start Date, Please try again." ) crypto_data = crypto_data_all context = { "currencies": currencies, "crypto": crypto_name, "crypto_data": crypto_data, "min_date_table": min_date_table, "max_date_table": max_date_table, } return render(request, "app_crypto/crypto_list.html", context) else: if sd == None or sd == "": … -
django Strings must be encoded before chechking?
i have a register form it work well and when i login the user it says that 'strings must be encoded before chechking ; and the error always show in login bcrypt.chekwp def getregisterpage(request): if request.method == "POST": firstname=request.POST.get('firstname') lastname=request.POST.get('lastname') email = request.POST.get("email") password = request.POST.get("password") hashed_password = bcrypt.hashpw(password.encode('utf-8'),bcrypt.gensalt()) if firstname and lastname and email and password : data=User(firstname=firstname,lastname=lastname,email=email,password=hashed_password) data.save() return redirect('login') else: return render (request,'register.html') ef getloginpage(request): if request.method == "POST": email = request.POST.get("email") password = request.POST.get("password") try: user = User.objects.get(email=email) except User.DoesNotExist: return redirect('register') if bcrypt.checkpw(password.encode('utf-8'),user.password): authenticated_user = authenticate(request,email=email,password=password) if authenticated_user: login(request, authenticated_user) messages.success(request, 'Logged in Successfully.') return redirect("home") else: messages.error(request, 'Authentication failed') else: messages.error(request, 'Invalid email or password.') return render(request, "login.html") -
When i try to login through new user and try to update its balance it is giving me {"detail": "User not found", "code": "user_not_found"} this error
My transaction API that i created where is this error occuring My serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'password', 'gender', 'age'] class LoginSerializer(serializers.ModelSerializer): username = serializers.CharField(required=True) password = serializers.CharField(required=True) class Meta: model = User fields = ['username', 'password'] class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['account_id', 'account_no', 'balance'] class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = ['account_id', 'transaction_type', 'transaction_balance'] My Views in Apps # only use serializer here in request body and response @swagger_auto_schema(method="post", request_body=LoginSerializer, responses={"200": 'LoginSerializer'}, operation_id="user Login", ) @api_view(['POST']) @permission_classes([AllowAny]) def login(request): # user can sign_in through this API serializer = LoginSerializer(data=request.data) if serializer.is_valid(): username = serializer.validated_data['username'] password = serializer.validated_data['password'] user_obj = User.objects.get(username=username, password=password) refresh = RefreshToken.for_user(user_obj) return Response({'msg': 'Logged In', 'refresh': str(refresh), 'access': str(refresh.access_token)}) return Response(serializer.errors) @swagger_auto_schema(method="post", request_body=TransactionSerializer, responses={"200": 'TransactionSerializer'}, operation_id="user signup transaction", ) @api_view(['POST']) # @authentication_classes(JWTAuthentication) # @permission_classes(IsAuthenticated) def transaction(request): # all read and update of balance logic here from this API serializer = TransactionSerializer(data=request.data) token = request.headers.get('Authorization') new_token = token.split(" ") decode_payload = jwt.decode(jwt=new_token[1], key=SECRET_KEY, algorithms=['HS256']) user = decode_payload['user_id'] if serializer.is_valid(): user_id = user transaction_type = serializer.validated_data['transaction_type'] acc_id = serializer.validated_data['account_id'] tran_bal = serializer.validated_data['transaction_balance'] if transaction_type == Transaction.TransactionType.DEPOSIT: acc_balance = Account.objects.get(id=acc_id.id, user_id=user_id) acc_balance.balance = acc_balance.balance … -
DJANGO: Query for select_related in view shows error
In my project with this ERM: I need to add equipment to an institute. Tried this: class EquipmentinLocationAdd(CreateView): model = EquipmentInstitute, Lot form_class = EquipmentInstituteForm template_name = 'Procure/equipmentininstitute_add.html' def get_success_url(self): return reverse('equipmentinstitute_sys', kwargs={'pk':self.object.Institute_id}) def get_initial(self): qs = Institute.objects.get( id = self.kwargs['pk'] ) initial = {'Institute': qs} return initial def get_context_data(self, **kwargs): # query for Institute Var1 = Institute.objects.all().get( id = self.kwargs['pk'] ) # query for Project Var4 = Project.objects.get(id = 5) # Here is my problem context = super().get_context_data(**kwargs) context ['queryset2'] = Lot.objects.all().values_list("LotTitle","Project") context.update({'LOK': Var1, 'LOKID': Var1.id, 'PR_id':Var4.id, 'PR':Var4}) return context Var1 is delivering data of the related institute. Var4 is supposed to get the related project. For testing purposes I worked with an fix 'id' of 5 However I need the related project of the selected institute but all my query efforts failed to retrieve the related project_id. (See Var4 in code) Need help! Thanks in advance Ben -
ImpropertyConfigured issues with customized password valiators in django
I´m writing customised password validators for django. But I get ImproperlyConfigured error -> ImproperlyConfigured django.core.exceptions.ImproperlyConfigured: The module in NAME could not be imported: auth.validators.UppercaseValidator. Check your AUTH_PASSWORD_VALIDATORS setting. settings.py (path : app/conf/settings/settings.py). -> AUTH_PASSWORD_VALIDATORS = [ {'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator'}, {'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 'OPTIONS': {'min_length': 12}}, {'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator'}, {'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'}, {'NAME': 'auth.validators.UppercaseValidator'}, ] validators.py (path: app/auth/validators.py). -> import re from django.core.exceptions import ValidationError from django.utils.translation import ugettext as _ class UppercaseValidator(object): def validate(self, password, user=None): if not re.findall('[A-Z]', password): raise ValidationError( _("The password must contain at least 1 uppercase letter, A-Z."), code='password_no_upper', ) def get_help_text(self): return _("Your password must contain at least 1 uppercase letter, A-Z.") I'm started to get a bit crazy because I cant see what the problem is pliz help me -
How to filter a Django model by properties of a reverse foreign key
I need to filter a Django model based on properties of a reverse foreign key and I'm not sure of the best way to do this. I have two models in which Products belong to a ProductRange class ProductRange(models.Model): pass class Product(models.Model): product_range = models.ForeignKey(ProductRange, related_name="products") is_archived = models.BooleanField() Product Ranges in which all products are set is_archived=True are to be considered archived, if any products are not marked as archived they are not considered archived. I need a way to filter Product Ranges based on this, i.e a filter that returns product ranges for which all products are archived. I'm aware I can filter by the related name: ProductRange.objects.filter(products__is_archived=False) However this returns product ranges where Any product is archived no all products. I'm also aware I can do the filtering in Python but I need this filter work on a large dataset and I'm sure there is a more efficient way to do this in the database. I've also considered using models.Subquery or models.Exists, however I feel like there is probably a simpler and more performant way of doing this that I am missing, also this would require a lot of refactoring to avoid a circular import. I feel … -
How to customize UI of Swagger (drf-yasg) to use dark mode?
So we have done our Django API documentation setup using drf-yasg, and I was wondering if it's possible to use dark mode in the documentation screen. For reference, the screen looks something like this: -
AttributeError: 'WSGIRequest' object has no attribute 'tenant'
I'm using django-tenants, following the Installation Guide, and I've created a simple project. Here's the scenario: I have a model named UnVerifiedTenants that stores company data, including their email and tenant ID. class UnVerifiedTenants(models.Model): """ model that Saves user email, depending upon below points 1. all emails from tenants for proper tenant utilization 2. all emails who just enquired and did not proceed further """ tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True, blank=True) email = models.EmailField(verbose_name="Email Address", unique=True) admin = models.BooleanField("Is user admin", default=False) created_on = models.DateField(auto_now_add=True) updated_on = models.DateField(auto_now=True) When users create their accounts on the registration page, the data is stored in this model. After users verify their phone number (which is stored in a different table), I migrate their schema. After completing the migration, they enter their email on the login page. I check their email, retrieve their schema, and create a URL to redirect them to their tenant domain for further authentication: class Login(generic.TemplateView): form_class = InitialAuthenticationForm template_name = "login.html" def post(self, request, **kwargs): email = request.POST["email"] scheme = "https" if self.request.is_secure() else "http" domain = settings.DOMAIN shared_user = AllUsersEmails.objects.filter(email=email).first() if shared_user: tenant_obj = shared_user.tenant try: tenant = tenant_obj.schema_name sub_url = f"accounts/enter-password/{encrypt(email.encode()).decode()}" url = f"{scheme}://{tenant}.{domain}/{sub_url}" shared_user.update_last_login() return redirect(url) … -
Django - large file upload - moving file from temp folder to final destination fails
Stumbled upon this error when upgrading Python, Django and Alpine to latest versions... and it's a weird one. The error occurs when I upload a file that is larger than FILE_UPLOAD_MAX_MEMORY_SIZE (set to 5MB). I have two development environments set up. One is local dev server (just normal py manage.py runserver), the other one is running under Docker(Windows) + Alpine linux + Apache2 + mod_wsgi which is also still a 'development' environment. This error occurs only under Docker environment and only when file exceeds max memory size. Under all other circumstances the upload works - even when file exceeds memory limit on local dev server. The error: Saving new order file to: customer_name/_web_portal/PendingOrders/7935/zip_03.zip Internal Server Error: /b2b_api/orders/ Traceback (most recent call last): File "/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/code/api/views.py", line 352, in dispatch return super().dispatch(request, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/usr/local/lib/python3.11/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise … -
DRF APITestCase but HttpResponseNotFound status_code=404
Hi I'm trying to make unittest by django and DRF but I have a problem when running test the below code is my tests, views, models code I check urls and runserver too and they work well. I need your help. tests.py class TestCohorts(APITestCase): def setUp(self): models.Cohort.objects.create(code=COHORT_CODE) def test_cohort(self): response = self.client.get("api/v1/cohort") print(response) data = response.json() self.assertEqual(response.status_code, 200, "status code is not 200.") views.py class CohortList(ListAPIView): queryset = models.Cohort.objects.all() serializer_class = serializers.CohortSerializer models.py class Cohort(models.Model): code = models.CharField(max_length=30) def __str__(self) -> str: return f"{self.code}" class Meta: db_table = "cohort" -
Should I render dynamic charts in Django or serve them from another webapp?
Here is this Django webapp hosted in a Apache2 server with mod_wsgi My question is: How do I add dynamic graphs to my webapp? In producion, in order to serve files, Nginx reverse proxy server catches the urls with the /static/ subdomain and serves the content (otherwise the request is redirected to apache) Google returns planty of ways to address the matter. Do you have any recomandation or relatable experience that I should know before choosing any? My concerns are: How clients update graph data without refreshing the whole page ? (I currentlly use htmx for rendering html) Should I use a second webapp to serve the content to nginx redirect? Is django-plotly-dash the most straight way? Will it work with htmx or else? I tried to periodically render an html with a plotly graph using htmx; resulted awful -
Django viewset: using get for list() only
I have this viewset where i wnat to use get method for list() only. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() def get_serializer(self, instance=None, *args, **kwargs): serializer = UserSerializer(method=self.action, instance=instance, *args, **kwargs) return serializer def get_permissions(self): if self.action == 'list': permission_classes = [IsAdminUser] elif self.action == 'update': permission_classes = [IsAuthenticated, IsOwner] elif self.action == 'create': permission_classes = [] else: raise ValueError(f"Invalid action: {self.action}") return [permission() for permission in permission_classes] I tried ti define http method names first, but list and retrieve both run for get method. Is there any other solution to this? -
User inbox feature in django project
Inbox feature in django project. I am working on this django project, and I want to implement an inbox feature in the project. The inbox will enable the admin if the website send messages to the users. Can someone help me out or point me in the right direction, I'll be so grateful. I am expecting the the users will be able to only read the admin message. -
Django: prevent Form to crash when akward date format is used
I have a form: class EditProfileForm(forms.ModelForm): template_name = 'users/edit_profile.html' def __init__(self, *args, **kwargs): super(EditProfileForm, self).__init__(*args, **kwargs) self.fields['email'].help_text = _( 'Providing your email would enable you to recover your lost password') class Meta: model = get_user_model() fields = ( 'first_name', 'last_name', 'email', 'birthday', 'language', 'headshot', ) with user model: class CustomUser(AbstractUser): birth_year = models.PositiveIntegerField( verbose_name=_('Birth year'), default=0) birthday = models.DateField(verbose_name=_( "birthday"), null=True, blank=True) headshot = models.ImageField(verbose_name=_('Avatar'), null=True, blank=True, default='user_headshots/user.png', upload_to="user_headshots/") language = models.CharField(verbose_name=_('Language'), max_length=10, choices=settings.LANGUAGES, default=settings.LANGUAGE_CODE) I had a user use a strange format for birthday "25,2,96", which led the django application to crash: The view users.views.edit_user_profile didn't return an HttpResponse object. It returned None instead. not much more information in the Traceback !?! Looking into the django code and internet, I was amazed that the DateField formfields did not come with embedded validators There are plenty of information on internet about setting specific dateformats for a specific DateField, but I wasn't able to find one kind of best practice that would work with all sort of localized date formats. Everything I found is very complicated for such a trivial issue, and I'm pretty sure there is a neat and easy to implement solution. Any suggestion? -
My python3 manage.py makemigrations or python manage.py makemigrations is erroring
I am trying to run th migration prompt in django and it isnt working. This is the error: @user: django_angular_auth_api % python3 manage.py makemigrations Traceback (most recent call last): File "/Users/user/django-angular-auth/django_angular_auth_api/manage.py", line 22, in main() File "/Users/user/django-angular-auth/django_angular_auth_api/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/init.py", line 442, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/init.py", line 436, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/base.py", line 412, in run_from_argv self.execute(*args, **cmd_options) File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/base.py", line 458, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/base.py", line 106, in wrapper res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/commands/makemigrations.py", line 137, in handle loader = MigrationLoader(None, ignore_no_migrations=True) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/loader.py", line 58, in init self.build_graph() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/loader.py", line 305, in build_graph self.graph.ensure_not_cyclic() File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/db/migrations/graph.py", line 284, in ensure_not_cyclic raise CircularDependencyError( django.db.migrations.exceptions.CircularDependencyError: users.0001_initial I added in a dependancy and did everything possible to try and fix it. wiped and redid db, and most other things i found online. -
ecommerce website with django adding many item to cart
` hello developers. Im using django for ecommerce website and I cant add item cart with number. For ex: I want to add 100 pieces of the same product with typing not increasing. Waiting your helps ` index.html <div class="card-footer p-0 no-gutters"> {% if product|is_in_cart:request.session.cart %} <div class="row no-gutters"> <form action="/#{{product.id}}" class="col-2 " method="post"> {% csrf_token %} <input hidden type="text" name='product' value='{{product.id}}'> <input hidden type="text" name='remove' value='True'> <input type="submit" value=" - " class="btn btn-block btn-light border-right"> </form> <div class="number-center col">{{product|cart_quantity:request.session.cart}} in Cart</div> <form action="/#{{product.id}}" class="col-2 " method="post"> {% csrf_token %} <input hidden type="number" name='product' value='{{product.id}}'> <input type="submit" value=" + " class="btn btn-block btn-light border-left"> </form> </div> {% else %} <form action="/#{{product.id}}" method="POST" class="btn-block"> {% csrf_token %} <input hidden type="number" name='product' value='{{product.id}}'> <input type="submit" class="float-right btn btn-light form-control" value="SEPETE EKLE"> </form> </div Thanks -
Best Explanation on the implementation of Dependency Injection in Python.?
I am a Software Engineer with significant amount of years of experience. I always desire using core development principles in my projects and these include using DI. which I have used alot in .NET projects and in Nodejs Projects. however I can't wrap my head around how DI actully works in python projects especially using FLask or Django. The examples I have seen are not really conidered DI to me. Would appreciate a good explanation. Thanks. I simply want to apply DI in future Django and Flask Projects. -
Django: no such table: auctions_user_user_permissions
I wrote the Django program and registered some products with the admin panel. After making some changes in the codes, I encountered some problems: 1- It is no longer possible to enter the admin panel and it gives this error. 2- None of the product information is displayed and it seems as if there is no data on the site. what is the problem? # item detail page in views.py def item_detail(request, bidid): bid_desc = List.objects.get(pk = bidid, active_bool=True) nowbids = Bidmodel.objects.filter(listb_id = bidid) return render(request, "auctions/item_detail.html",{ "list": bid_desc, "comments" : Comments.objects.filter(listc_id = bidid), "now_bid": minbid(bid_desc.first_bid, nowbids), }) index.html: {% extends "auctions/layout.html" %} {% block body %} <h2>Active Listings</h2> {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif %} <div> {% for item in items %} <div> <img src= {{ item.image.url }} alt = "{{item.title}}"><br> <a>{{ item.title }}</a><br> <a>{{ item.category }}</a><br> <a><a>Frist Bid: </a> {{ item.first_bid }} $ </a><br> <a href="{% url 'item_detail' item.id %}">View Product</a> </div> {% endfor %} </div> {% endblock %} item_detail.html: {% extends "auctions/layout.html" %} {% block body %} {% if messages %} {% for message in messages %} <div>{{ message }}</div> {% endfor %} {% endif … -
WeasyPrint: Image not showing on linux (ubuntu)
I am using weasyprint it working on window perfectly and also it is working on linux when I used this string in html file like weasyprint my.html my.pdf It perfectly show image but when I do the below code so the image not showing I html_string = '<img src="http://domain_name/static/assets/images/logo/logo.png" alt = "Logo" /> <h1>images</h1>' # Create a PDF object from the HTML string #pdf = weasyprint.HTML(string= html_string, base_url=request.build_absolute_uri()).write_pdf(presentational_hints = True, stylesheets=[weasyprint.CSS(string='@page { size: letter; }')]) # # Create an HTTP response with the PDF content response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="marksheet.pdf"' response.write(pdf) return response I used absolute_url but not showing images nothing get any idea why it not showing image