Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not hashing password. Unexpected keyword argument 'password2'
I have three different questions. They're all related to each other. 1 - I get an error when I add password2 or confirm_password field. Got a `TypeError` when calling `CustomUser.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `CustomUser.objects.create()`. You may need to make the field read-only, or override the UserCreateSerializer.create() method to handle this correctly. TypeError: CustomUser() got an unexpected keyword argument 'confirm_password' 2 - Without any validate when I only have password field. I am not getting any errors but passwords are not hashed. 3 - When I want to create user using shell. Even if I leave all the fields blank, I can create an empty user without any errors. -
Django + uwsgi = Sqlite: cannot operate on a closed database
I have a Django application that works fine when running it with python manage.py runserver. After I added uwsgi, I frequently started to encounter the error Cannot operate on a closed database. The very same endpoint that raises this error works fine if I call it manually from a browser. The errors occur usually after a few hundreds / thousands call (coming really fast) which are made by another service. Here's my uwsgi settings: [uwsgi] chdir = ./src http = :8000 enable-threads = false master = true module = config.wsgi:application workers = 5 thunder-lock = true vacuum = true workdir = ./src add-header = Connection: Keep-Alive http-keepalive = 65000 max-requests = 50000 max-requests-delta = 10000 max-worker-lifetime = 360000000000 ; Restart workers after this many seconds reload-on-rss = 2048 ; Restart workers after this much resident memory worker-reload-mercy = 60 ; How long to wait before forcefully killing workers lazy-apps = true ignore-sigpipe = true ignore-write-errors = true http-auto-chunked = true disable-write-exception = true -
Python/Django Test: Mock Verification Service
I am attempting to write a test for a service that uses the Twilio Verification service. I am basing my test off of the following article: https://www.twilio.com/blog/testing-twilio-applications-python-pytest However, I cannot seem to properly target the client.services.verify.services method from the TwilioRest module as the request always gets sent to the Twilio server. Has anyone had any success properly mocking this method ? verification/services.py from decouple import config from twilio.rest import Client from twilio.base.exceptions import TwilioRestException from .config import INVALID_PARAMETER, TOO_MANY_REQUESTS account_sid_production = config("TWILIO_ACCOUNT_SID_PRODUCTION") auth_token_production = config("TWILIO_AUTH_TOKEN_PRODUCTION") verify_service_sid = config("TWILIO_VERIFY_SERVICE_SID") client = Client(account_sid_production, auth_token_production) def verification_service_create(phone_number, channel="sms"): try: client.verify.services(verify_service_sid).verifications.create( to=phone_number, channel=channel ) return ( True, "Check your phone for verification code", "Verification Code successfully sent", ) except TwilioRestException as error: if error.code == INVALID_PARAMETER: return ( False, "Phone value is incorrectly formatted or is not a valid phone number.", "Use strict E.164 formatting, including the + sign," "for phone numbers in the To parameter. Example: +15017122661.", ) if error.code == TOO_MANY_REQUESTS: return ( False, "You have sent too many requests to this service. Please try again later.", "You have sent too many requests to this service. Please try again later.", ) return ( False, "Internal Error", "Internal Error", ) verification/tests/services/test_verification_service_create.py from unittest.mock … -
How to fix a faulty decrease product quantity button for a django ecommerce store?
I'm trying to wire up a decrease quantity (minus) button to reduce the number of products in a shopping cart for a django e-commerce store. However, when I click the minus button either A) nothing happens, or B), if I click the minus button after increasing the quantity with the plus button, the minus button performs the same task as the 'update' button, i.e. confirming the quantity change to the newly higher number of products. The relevant views.py function: def adjust_cart_item_qty(request, item_id): # changes number of items in the cart qty = int(request.POST.get('qty')) cart = request.session.get('cart', {}) if qty > 0: cart[item_id] = qty else: cart.pop(item_id) request.session['cart'] = cart return redirect(reverse('cart')) The app-level urls.py: from django.urls import path from .views import CartView from . import views urlpatterns = [ path('', CartView.as_view(), name='cart'), path('add/<item_id>', views.add_cart_item, name='add_cart_item'), path('adjust_cart/<item_id>', views.adjust_cart_item_qty, name='adjust_cart'), path('remove_cart_item/<item_id>', views.remove_cart_item, name='remove_cart_item'), ] The html template: {% extends 'base.html' %} {% load static %} {% block content %} {% if cart_items %} <div class="row"> <div class="col-md-12 text-center mt-3 mb-3"> <h1>Your shopping cart</h1> </div> </div> {% for item in cart_items %} <div class="row"> <div class="col-md-6"> <div class="card card-wide"> <ul class="list-group list-group-flush"> <li class="list-group-item text-center text-uppercase">Course: {{ item.course.title }} </li> <li class="list-group-item">Level: {{ … -
Port doesnt respond
After python manage.py runserver , all goes well,when I use the link http://127.0.0.1:8000/ generated it fails to open the Django project on windows 10 completely, I can't figure out the problem. I've tried disabling proxies and firewalls and antivirus but still unable to open.Also tried restarting the computer and entire procedure,spent hours on this, what could be the problem -
Deploy Sphinx docs on django server
Recently I have been creating docs usign sphinx. Now when the docs are done I want to deploy them on my web app under like /docs/ url. Is here any good tool that is capable of doing that ? So far I found tool that is able to deploy the docs under url but the docs look awful - it takes the json created by make and render the data… https://github.com/carltongibson/django-sphinx-view Thanks for any ideas. -
Need to save all answers from a user on every questions related on a specific Quiz
I want to save after submitting all answers from a user of all questions related on a specific Quiz. The logical is : I've got Quiz, Questions. Question car link to Quiz and when I choose a quiz all questions link to are shown on webpage with javascript (design). After submiting I need to get all checkbox checked and save into UserResponse. Models class Question(models.Model): objects = None question = models.CharField(max_length=200, null=True) description = models.CharField(max_length=255, null=True) question_pic = models.ImageField(upload_to='poll/', storage=fs, null=True) choices = models.ManyToManyField(Answer, related_name='QuestionsChoices') mandatory = models.BooleanField(default=True) multiple = models.BooleanField(default=False) randomize = models.BooleanField(default=False) class Quiz(models.Model): STATUS_CHOICES = ( (1, 'Draft'), (2, 'Public'), (3, 'Close'), ) nom = models.CharField(max_length=200, null=False) theme = models.ForeignKey(Theme, null=False, on_delete=models.CASCADE) questions = models.ManyToManyField(Question, related_name='Quizs') status = models.IntegerField(choices=STATUS_CHOICES, default=1) published = models.DateTimeField(null=True) date_added = models.DateTimeField(auto_now_add=True) date_modified = models.DateTimeField(auto_now_add=True) class QuizInstance(models.Model): objects = None """ A combination of user response and a quiz template. """ player = models.ForeignKey(User, on_delete=models.CASCADE) quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE) start_quiz = models.DateTimeField(auto_now_add=True) score = models.IntegerField(default=0) complete = models.BooleanField(default=False) class UserResponse(models.Model): objects = None """ User response to a single question. """ quiz_instance = models.ForeignKey(QuizInstance, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) response = models.ManyToManyField(Answer, related_name="UserResponses") time_taken = models.DateTimeField(auto_now_add=True) time_taken_delta = models.DateTimeField(blank=True) VIEWS (to show all … -
Django - __init__() missing 1 required positional argument: 'request'
I have the following error: CompareFormTransporterCompany.__init__() missing 1 required positional argument: 'request'. Here is my form in forms.py: class CompareFormTransporterCompany(forms.ModelForm): file = forms.FileField(label="File (CSV, XLSX, XML) ", required=True) name_transporter = forms.ModelChoiceField(label='Choose transporter', required=True, queryset=Transporter.objects.all()) class Meta: model = CheckFile fields = ['file',] def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request def clean(self): super().clean() uploaded = parse_csv(self.request.FILES['file']) In views.py: class ResultFormView(FormView): """ View to show results of comparison between two files. """ template_name = 'tool/upload.html' form_class = CompareFormTransporterCompany success_url = reverse_lazy('tool:result') And my model in models.py if needed: class CheckFile(models.Model): name = models.CharField(max_length=200, blank=True) month = models.DateField(blank=True, null=True) timestamp = models.DateTimeField(blank=True, null=True) profile = models.CharField('Choix du profil', blank=False, choices=PROFILE_CHOICES, max_length=100, default="Client") file = models.FileField(blank=True, null=True, upload_to="uploads/", validators=[validate_file_extension]) def __str__(self): return self.name class Meta: verbose_name = "file" verbose_name_plural = "files" I have been trying a lot of different solutions but I don't understand the error. Could you please help me? -
Initialize different field with different parameter in serializer depending on passed variable
I am trying to initialize different field (object with different parameter) by specifying proper parameter and pass it to serializer somehow. Here's what I mean: class ImageSerializer(FlexFieldsModelSerializer): image = VersatileImageFieldSerializer(sizes=custom) class Meta: model = UserImage fields = ['pk', 'image'] In this class I want to pass to the VersatileImageFieldSerializer different sizes (replace 'custom' variable) from the view. I know that I can pass the context and read the value from there, and It works perfectly fine. There is only one problem: I cannot refer to self.context in the moment I define variables. To solve it I tried to override the constructor and create this variable from there. Here is how I did it: def __init__(self, *args, **kwargs): self.image = VersatileImageFieldSerializer(sizes=self.context.get('custom')) super(ImageSerializer, self).__init__(*args, **kwargs) With this approach I got error 'ImageSerializer' object has no attribute 'parent' and I coulnd't find a solution for this, so I tried to implement SerializerMethodField and return this type of object like this: image = serializers.SerializerMethodField() def get_image(self, obj): return VersatileImageFieldSerializer(sizes=self.context.get('custom')) but VersatileImageFieldSerializer is not serializable. I ran out of ideas and solutions and also slowly running out of time. Is there any way I could achieve my goal? -
Integrity error (FOREIGN KEY constraint field) raised when I try to save request.POST from a model form
I am working on a commerce app, (with django but very new to it) where a user can create a listing through a ModelForm called ListingForm that inherits from a Model called Listing.Here is the code for the the Listing model and ListingForm: from django.contrib.auth.models import AbstractUser from django.db import models class Listing(models.Model): NAME_CHOICES = [ ('Fashion', 'Fashion'), ('Toys','Toys'), ('Electronic','Electronics'), ('Home', 'Home'), ('Other', 'Other') ] import datetime title = models.CharField(max_length= 64) date_made = models.DateField(default= datetime.date.today()) description = models.TextField() user = models.ForeignKey(User, to_field='username', on_delete=models.CASCADE, related_name='user_listings', null=True) starting_bid = models.DecimalField(decimal_places=2, max_digits=264, default=10.00) image_url = models.CharField(blank=True, max_length=1000) category = models.ForeignKey(Category, on_delete=models.CASCADE, to_field='name', related_name='category_listings', default=NAME_CHOICES[4][0]) listing_category = models.CharField(max_length=12, choices=NAME_CHOICES, null=True, default=NAME_CHOICES[4][0]) is_active = models.BooleanField(default=True) def __str__(self): return f'{self.title}' Here is the code for the ```ListingForm``: from .models import Listing from django.forms import ModelForm class ListingForm(ModelForm): class Meta: model = Listing exclude = [ 'date_made', 'user', 'category', 'is_active', ] The Listingmodel also has foreignkeys to and within the models User,Category and Bid. Here is the code for these models(same imports as those shown for Listing model): class User(AbstractUser): def __str__(self): return f'{self.username} ' class Category(models.Model): NAME_CHOICES = [ ('Fashion', 'Fashion'), ('Toys','Toys'), ('Electronic','Electronics'), ('Home', 'Home'), ('Other', 'Other') ] name = models.CharField(max_length=12, choices= NAME_CHOICES, unique=True) def __str__(self): … -
Django - Adding a primary key to an existing model with data
This is the existing model in a djnago app: class Task_Master_Data(models.Model): project_id = models.ForeignKey(Project_Master_Data, on_delete=models.CASCADE) task_created_at = models.DateTimeField(auto_now_add=True) task_updated_at = models.DateTimeField(auto_now=True) task_name = models.CharField(max_length=200, null=True) I want to add a new field (which will be a primary key): task_id = models.AutoField(primary_key=True, null=False) When I am making migrations from the terminal, it will provide me with the option of adding a default value, but it will, understandably, bring an error of: UNIQUE constraint failed: new__main_task_master_data.task_id What would be the best way forward for this kind of a scenario without having to delete all the data. -
Django. Object of type Url is not JSON serializable
I am writing parser for website. I have 2 models: Url (id and site url) and News (all the data that will be parsed) I made a form which allows users to eneter the link of website which is automatically saved in db. And also I have a signal which starts to parse data as soon as an Url instanced is saved. But the point is that when I call the function hackernews_rss which parses the data I Get an error kombu.exceptions.EncodeError: Object of type Url is not JSON serializable I don't know how to fix it as in order to save all the parsing result a need to have a Url instance because I have OneToManeRelation models: class Url(models.Model): link = models.CharField( max_length=200, blank=True ) def get_absolute_url(self): return f'/parser/search/' class News(models.Model): domain = models.CharField(max_length=200) link_id = models.ForeignKey(Url, on_delete=models.CASCADE) link = models.CharField(max_length=200, blank=True) create_date = models.DateTimeField() update_date = models.DateTimeField() country = models.CharField(max_length=200, null=True) is_dead = models.BooleanField() a = models.CharField(max_length=200, null=True) ns = models.CharField(max_length=200, null=True) cname = models.CharField(max_length=200, null=True) mx = models.CharField(max_length=200, null=True) txt = models.CharField(max_length=200, null=True) tasks: @shared_task(serializer='json') def save_function(article_list): print('starting') new_count = 0 for article in article_list: try: print(article['link_id']) News.objects.create( link=article['link'], domain=article['domain'], create_date=article['create_date'], update_date=article['update_date'], country=article['country'], is_dead=article['is_dead'], a=article['a'], ns=article['ns'], cname=article['cname'], … -
How to develop big projects?
I just have interesting question. Is it safety to use open cource systems (CMS) and/or frameworks (any) to build an e-commerce projects like Amazon, E-bay etc to make international online-shopping? How are the big projects developing nowadays? And do you know any famous apps, web-sites, projects used only frameworks? -
Django chained foreign key forms
Apologies ahead of time if there is an easy answer to this in the docs or elsewhere, but I'm working on my first django project, I think I'm on my last big obstacle, and my eyes are bleeding from digging through examples, tutorials and docs that aren't related to what I'm trying to do. https://www.youtube.com/watch?v=NiWAiIiNYDc This video is probably the closest to what I'm trying to do, but it requires mysql stored procedures, and it seems I should be able to do this in sqlite. At a high level, here is what I want: If we have a store with multiple items, I want to categorize each item on two levels Upper_Category: name Sub_Category: name parent -- foreign key: Upper_Category So, each item would look like: Item: name description ...etc... category -- foreign key: Sub_Category Filled in, they might be: Upper_Categories-- Food Drink Dishes Sub_Categories: Meat: parent=Food ... Beer: parent=Drink It seems to me that I should be able to wrap this all into an editable formset based on 'Item' where each item includes a reference to what Upper_Category it belongs to Category | Sub-Category | Name | Description ... "Drink" | "Beer" | "Something IPA" | "beer description.." ...etc … -
Django Cant Catch error from pandas dataframe
I try to catch an error that shows in the template that said: ArrowTypeError at /user_area/absent/2840 Atlantic Ave/ ("Expected bytes, got a 'int' object", 'Conversion failed for column ZipCode with type object') Request Method: GET Request URL: http://127.0.0.1:8000/user_area/absent/2840%20Atlantic%20Ave/ Django Version: 3.2.12 Exception Type: ArrowTypeError Exception Value: ("Expected bytes, got a 'int' object", 'Conversion failed for column ZipCode with type object') Exception Location: pyarrow/error.pxi, line 122, in pyarrow.lib.check_status my code is like : try: return pd.read_feather(os.path.join(cache_folder, file)) except Exception as e: print(e) return get_api_info(request_items, url_requested, now) what I want is to as soon the ArrowTypeError comes up, the Except return get_api_info(). is there anyway way I can do that? thanks -
Forbidden (CSRF token missing or incorrect.): /audio
i have website with button to upload audio mp3 on a post. the problem, when i clicked the button, it's open new / (http://localhost:8000/audio) actually just http://localhost:8000. and when i see terimal, there's error message Forbidden (CSRF token missing or incorrect.): /audio at the same time, there's error at my website with error message Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect. In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used correctly. For POST forms, you need to ensure: Your browser is accepting cookies. The view function passes a request to the template's render method. In the template, there is a {% csrf_token %} template tag inside each POST form that targets an internal URL. If you are not using CsrfViewMiddleware, then you must use csrf_protect on any views that use the csrf_token template tag, as well as those that accept the POST data. The form has a valid CSRF token. After logging in in another browser tab or hitting the back button after a login, you may need to reload the page with the form, because … -
Unable to get primary key in django model
I am trying to create an invoicing app in django class CustomerDetailsModel(models.Model): Customer_ID = models.IntegerField(unique=True,auto_created=True,primary_key=True) Civil_ID = models.CharField(max_length=50,unique=True) Customer_Name =models.CharField(max_length=200,unique=True) phone_number_1 = models.CharField(max_length=20,blank=True) phone_number_2 = models.CharField(max_length=20,blank=True,null=True) Customer_Disc = models.TextField(blank=True,null=True) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return self.Customer_Name class InvoiceModel(models.Model): Invoice_ID = models.IntegerField(unique=True,auto_created=True,primary_key=True) Customer_ID = models.ForeignKey(CustomerDetailsModel,on_delete=models.CASCADE) Civil_ID = models.IntegerField(unique=True) Customer_Name =models.CharField(max_length=200,unique=True) phone_number_1 = models.CharField(max_length=8) InvNo = models.IntegerField() Item_ID = models.IntegerField() Item_Name = models.CharField(max_length=200) Rate = models.DecimalField(max_digits=8,decimal_places=2) TotQ = models.DecimalField(max_digits=8,decimal_places=2,default=0.0) TotAmount = models.DecimalField(max_digits=8,decimal_places=2,default=0.0) Status = models.CharField(max_length=200) Date = models.DateField(auto_created=True) Month = models.CharField(max_length=3) created_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) def __str__(self) -> str: return str(self.BookNo) This are the the two models the I use. I had no issue creating a new customer but when it came to creating the invoice it was showing the value error for Customer_ID 'ValueError: save() prohibited to prevent data loss due to unsaved related object 'Customer_ID'.' After using breaker points in VS Code, I found out out that Customer_ID field was returning 'None'. I tried deleting the db and start over but I was still getting the same results this is the function for creating invoice def update_invoice(cid,data): inv = InvoiceModel( Customer_ID = cid, Civil_ID = cid.Civil_ID, Customer_Name =cid.Customer_Name, phone_number_1 =cid.phone_number_1, InvNo = data['incno'] … -
Connect Django with Azure postgres sql wusing managed identity in azure
How to configure Azure postgres sql database in django settings.py using Managed Identity In Azure -
Django AdminInline on many-to-many relationship
I have two models like this: class ArtCollection(models.Model): # nothing important in this case class Artwork(models.Model): ... name = models.CharField(max_length=200, null=True, blank=True) art_collections = models.ManyToManyField("ArtCollection", related_name="artworks") image = models.ImageField(...) Recently, I've change the relationship between them from FK for ArtCollection on Artwork model to m2m (as seen as above). What I would like to have now is something that I had before, particulary ArtworkInline in admin panel on ArtCollection change view (editable artwork fields like name, image change and so on). But it doesn't work. The only solution I've came across is this one (I know I should make an image preview rather than display its name - but its just an example): from inline_actions.admin import InlineActionsMixin, InlineActionsModelAdminMixin class ArtworkInline(admin.StackedInline): model = ArtCollection.artworks.through extra = 0 fields = ['artwork_image'] readonly_fields = ['artwork_image'] def artwork_image(self, instance): return instance.artwork.image artwork_image.short_description = 'artwork image' class ArtCollectionAdmin(InlineActionsModelAdminMixin, admin.ModelAdmin): ... inlines = [ArtworkInline] Is it possible to have the editable fields in m2m relationship in inline django panel? I also use grappeli and custom template for inline (which are useless after changing the relationship - they have worked pretty well with FK, now I can have only readable_fields on default template). {% extends 'admin/stacked_inline.html' %} … -
Python Django cx_Oracle stored procedure output parameter get data
I am able to successfully call the stored procedure but unable to retrieve the data in the OUT parameter. The out_var variable does not contain the result. What am I doing wrong? I have the following code in Django: def call_stored_procedure(in_var_1: int, in_var_2: str): with connections['DB_KEY'].cursor() as cursor: out_type = connections[db].connection.gettype("CUSTOM_SCHEMA.CustomTableOfType") out_var = cursor.var(out_type).var x = cursor.callproc("CUSTOM_SCHEMA.CUSTOM_PACKAGE.CustomProc", (in_var_1, in_var_2, out_var )) return x, out_var The following database settings in settings.xml DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'DB_KEY': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'xxxx.xxxx.xxxx:1111/XXX', 'USER': 'xxxxxx', 'PASSWORD': 'xxxxxxx', } ] The following is the stored procedure that I call: PROCEDURE CustomProc( in_var_1 IN number, in_var_2 IN varchar2, out_var OUT CUSTOM_SCHEMA.CustomTableOfType ) IS ... BEGIN ... END The CUSTOM_SCHEMA.CustomTableOfType looks like this: TYPE CustomTableOfType AS TABLE OF CUSTOM_SCHEMA.CustomType; CUSTOM_SCHEMA.CustomType looks like this: TYPE CustomType FORCE AS OBJECT ( XXX NUMBER(6), YYY DATE, ZZZ NUMBER(3), CONSTRUCTOR FUNCTION CustomType RETURN SELF AS RESULT); The data in the out parameter is missing from the bound object. -
How to use prefetch_related in django rest api with foreying key and heritage
I am working on this Django project, it uses heritage and foreign keys for its models. These are the models: class SetorFii(models.Model): name = models.CharField(max_length=255) class Asset(models.Model): category = models.ForeignKey( Category, related_name='categories', on_delete=models.CASCADE) ticker = models.CharField(max_length=255, unique=True) price = models.FloatField() class Fii(Asset): setor_fii = models.ForeignKey( SetorFii, null=True, default=None, on_delete=models.CASCADE, related_name="setor_fiis") Class Crypto(Asset): circulating_supply = models.FloatField(default=0) class PortfolioAsset(models.Model): asset = models.ForeignKey(Asset, on_delete=models.CASCADE) I would like to get the field setor_fii in the PortfolioAssetSerializer, That is what I tried without success. I get this error message: Cannot find 'setor_fii' on PortfolioAsset object, 'setor_fii' is an invalid parameter to prefetch_related() Would like some help to achieve that. The serializer: class PortfolioAssetSerializer(serializers.ModelSerializer): category = serializers.CharField(source='asset.category.name') setor_fii = serializers.CharField(source='asset.setor_fii') class Meta: model = models.PortfolioAsset fields = ( 'id', 'category', 'setor_fii' ) The view class PortfolioAssetList(generics.ListAPIView): serializer_class = serializers.PortfolioAssetSerializer def get_queryset(self): return models.PortfolioAsset.objects.filter(portfolio_id=self.kwargs['pk']).prefetch_related('setor_fii') -
1054, "Unknown column" exception upon adding nonexisting field in Django 4.0
I have struck upon a problem of adding additional field. I want it to be boolean, but it doesn't actually matter which type the field will be, because I also tried to create an integer field instead of boolean with getting the same exception. The exception I get is: django.db.utils.OperationalError: (1054, "Unknown column 'salary_profile.confirmation_link_sent' in 'field list'") And here is the model I am talking about with the field already added in the last line: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) birth_date = models.DateField(null=True) employment_date = models.DateField(null=True) position = models.ForeignKey('Position', on_delete=models.PROTECT, null=True) attestation_date = models.DateField(blank=True, null=True) dismiss_date = models.DateField(blank=True, null=True) photo = models.ImageField(blank=True, null=True, upload_to=user_directory_path) email_is_confirmed = models.BooleanField(default=False) confirmation_link_sent = models.BooleanField(default=False) This problem encountered both in sqlite and mysql. So far the only answers to the problem I found on the internet were "to delete the whole base and start again", which to put it lightly - ridiculous, but also adding this field manually in the database itself. But I hardly see it as a solution because imagine I have to add 20 of such fields tomorrow, I will have to do those manual additions as well? And I must add that many answers are getting back to django … -
TypeError:unsupported format string passed to Series.__format__
I am trying to print time in 12 hour clock format but django throws TypeError. works fine for python but shows error in django Thanks is Advance def solve(s, n): h, m = map(int, s[:-2].split(':')) h =h% 12 if s[-2:] == 'pm': h =h+ 12 t = h * 60 + m + n h, m = divmod(t, 60) h =h% 24 if h < 12: suffix = 'a' else: suffix='p' h =h% 12 if h == 0: h = 12 return "{:02d}:{:02d}{}m".format(h, m, suffix)``` -
how to get response with message,error, status in django rest framework
HI Everyone i am creating api using drf but i want response with different formet, below i have mention my current response and expected response.how can achieve me my expected api response formet. views.py class TeamlistViewset(viewsets.ViewSet): def list (self,request): team=Team.objects.all() serializer=TeamSerializer(team,many=True) return Response(serializer.data) api response [ { "id": 1, "name": "Deadly Shark" } ] expected api response { "message": "list retrieval", "error": false, "code": 200, "results": { "totalItems": 1, "pageData": [ { "id": 1, "name": "Deadly Shark" } ], "totalPages": null, "currentPage": 0 } } -
python manage.py makemigrations says table already exists in Django project
I am trying to get a coworker of mine up and running with a project I have already created. When we try to run the server it says one of the tables already exists. We googled it and tried to makemigrations and migrate --fake from posts like this Django : Table doesn't exist but still get the same result. Deleting the tables in the database isn't an option because its connecting to some production data. How can I get around this? The traceback is below. Traceback (most recent call last): File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\db\backends\mysql\base.py", line 74, in execute return self.cursor.execute(query, args) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\MySQLdb\cursors.py", line 209, in execute res = self._query(query) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\MySQLdb\cursors.py", line 315, in _query db.query(q) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\MySQLdb\connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1146, "Table 'xpotoolsdb.xpotoolshome_site' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\core\management\base.py", line 366, in execute self.check() File "C:\Users\tmartinez005\GIT\GXOTools.com-xpotools\gxotools\lib\site-packages\django\core\management\base.py", line …