Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I properly handle prefix and delete items
I have a formset in django, Some forms have been deleted and some have not, plus I have a ForeignKey link into the model I am using models.py: class Client(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) group = models.CharField(max_length=50) class Meta: # make sure we can have unique phone number to each client unique_together = ('phone_number', 'group',) class ExtraPhoneData(models.Model): client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) group = models.CharField(max_length=50) phone_number = PhoneNumberField(blank=False) class Meta: # make sure we can have unique phone number to each client unique_together = ('phone_number', 'group',) forms.py: class AddClientPhonetData(AjaxFormMixin, forms.ModelForm): template_name = 'client/phone_form.html' class Meta: model = ExtraPhoneData fields = ('phone_number',) widgets = { 'phone_number': forms.TextInput(attrs={'class':'form-control', 'placeholder': 'Extra Phone Number'}), } FormsetAddExtraPhoneData = inlineformset_factory(Client, ExtraPhoneData,form=AddClientPhonetData, extra=1, fields=('phone_number',), can_delete=True) views: def CreateClient(request, template='client/new_client.html'): if request.method == 'POST': updated_request = UpdateGroupAndCreator(request, uuid) forms = {} forms["extra_phone"]= FormsetAddExtraPhoneData(updated_request,prefix="extraPhone") forms["client_form"] = AddClientForm(updated_request, prefix="basicData") if forms["extra_phone"].is_valid() and forms["client_form"].is_valid(): # save client obj client = forms["client_form"].save() # save formsets formset_almost_commit = forms["extra_phone"].save(commit=False) # delete objects of flaged as deleted for obj in forms["extra_phone"].deleted_objects: obj.delete() # add ForeignKey to the rest and save them for commits in formset_almost_commit: commits.client = client_obj commits.save() # -> yield error relation "client_extraphonedata" does not exist LINE 1: INSERT INTO "client_extraphonedata" … -
Is there a way to automatically include text fields in a Django form?
I am creating a form in Django. There are some static fields included but I also want to include some fields based on a csv file. However, I can't figure out how to make those text fields part of the form submission. forms.py class OptimizerForm(forms.Form): no_lineups = forms.IntegerField(label='Number of Lineups', min_value=1, initial=1) min_deviation = forms.DecimalField(label='Minimum Deviation %', min_value=0, initial=0) max_deviation = forms.DecimalField(label='Maximum Deviation %', min_value=0, initial=15) randomize = forms.BooleanField(label='Randomize Lineups', initial=True) views.py def create_optimizer(request): if request.method == 'POST': form = OptimizerForm(request.POST) if form.is_valid(): no_lineups = form.cleaned_data['hjk'] with open('C:\\Users\\Charlie\\Desktop\\Fantasy Fire\\website\\optimizer\\lineups.csv') as myfile: response = HttpResponse(myfile, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=lineups.csv' return response else: form = OptimizerForm() df = Optimizer.get_daily_roster( 'C:\\Users\\Charlie\\Desktop\\Fantasy Fire\\website\\optimizer\\Predictions.csv') df = df.drop(columns=['Name + ID', 'Game Info', 'Unnamed: 0', 'Unnamed: 0.1', 'name']) df = df.rename(columns={'TeamAbbrev': 'Team', 'AvgPointsPerGame': 'Predicted FP'}) df['Predicted FP'] = df['Predicted FP'].apply(lambda x: round(float(x), 2)) df['Predicted FP'] = df['Predicted FP'].apply( lambda x: "<input type='text' value=" + str(x) + " id='id_predicted_fp'>") df['Min Exposure'] = "<input type='text' value=" + str(0) + ">" df['Max Exposure'] = "<input type='text' value=" + str(100) + ">" html_table = df.to_html(index=False, justify='left', escape=False, classes=[ 'table table-bordered table-striped table-hover table-responsive table-sm, container-fluid']) return render(request, 'optimizer/optimizer.html', {'form': form, 'player_table': html_table}) optimizer.html {% extends "optimizer/base.html" %} {% block content … -
Implement inline grid editing as global function
Hello I have tried to implement inline grid editing in my datatable .It's working.... But I need to implement the inline editing in other tables .... So I would like to make a global function for this ..... But it shows some error .... This is my code .... var slug='sales' window.drawDataTable = function(){ "columnDefs": [ { targets: [10,11,27,28], render:function(data){ return moment(data).format('LLLL'); }, }, {'targets': '_all', 'createdCell': function (td, cellData, rowData, row, col) { $(td).attr('data-pk', rowData['id']); const key = Object.keys(rowData)[Object.values(rowData).indexOf(cellData)]; $(td).attr('data-name', key ); }}, { targets: [0,1], className: ""}, //{targets:'_all',className:"querytruncate"}, { "targets": [29,30], "orderable": false } ], "fnDrawCallback":function(){ $('#data_table_list td').editable({ params: function(params) { var pk = $(this).data('pk'); var name = $(this).data('name'); var data = {}; data['field'] = name; data['value'] = params.value; data['id'] = pk; data['slug']=slug; return data; }, url: "{% url 'request_access' %}", success : function(data) { if (data.status == true) { toastr.success(data.msg); } else { toastr.error(data.msg); } }, error: function () { toastr.error('Something went wrong'); } }); }, } So I try to implement like this.... in my core.js var inline = function(){ $('#data_table_list td').editable({ params: function(params) { var pk = $(this).data('pk'); var name = $(this).data('name'); var data = {}; data['field'] = name; data['value'] = params.value; data['id'] = pk; … -
How to redirect with middleware in Django
I wrote this program so that the user would be moved to my target page if it had certain conditions. This is my custom Django middleware: def check_userprofile_middleware(get_response): def middleware(request): response = get_response(request) if request.user.is_authenticated: # Profile conditions goes here. if profile_condition: return redirect(reverse('base:edit_user_profile')) return response return middleware if I use return in if statement: Redirect to 'base:edit_user_profile' url, But after that I see this error on browser: This page isn’t working 127.0.0.1 redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS If I don't use "return in "if" statement: Everything goes correct,except redirection! What is worng with this? -
Singleton object behaviour in Django
Consider I want to create a singleton object for each user accessing a particular feature in the website. This object is not a Model. class NavApi: __instance = None @staticmethod def get_instance(): """ Static access method. """ if NavApi.__instance is None: Client() return NavApi.__instance In views file @csrf_exempt def get_folder_tree(request): if request.method == "POST": nav_api = NavAPI.get_instance() folders = nav_api.listing_folders(request.POST.get('id')) return render(request, "folder_tree.html", {'folders': folders, 'page1': False}) @csrf_exempt def get_prev_folder_tree(request): if request.method == "POST": nav_api = NavAPI.get_instance() page1,folders = nav_api.listing_prev_folder_tree() return render(request, "folder_tree.html", {'folders': folders,'page1':page1}) The reason for using Singleton is that the class object has few members which defines the state of the folder/contents/current folder_id etc. And it should not be created for every view. It needed to be reused But when I tried to run it as public, using ngrok and shared the linked to my friend, and testing the navigation features, We ended up using the same singleton object. When I was browsing contents of Folder A, and he was browsing contents of Folder B, we ended up recieving contents of the same folder(either A or B). How to overcome this? -
How To Fix Auto Login In Dajngo?
How To Fix Auto login When I go to this URL like this: 127.0.0.1:8000/profile/1 When I see If Someone go to that URL so Django login him without password and username ERROR: How To Fix Auto Login In Django You Can See The Gif For More Details: Views.py def profile_detail(request,pk): user = get_object_or_404(User, pk=pk) model = user_register_model() return render(request,'profile_detail_view.html',{'user':user,'model':model,}) urls.py from . import views from django.urls import path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.index,name='index'), path('accounts/signup/', views.user_reg,name='register'), path('profile/<int:pk>',views.profile_detail,name='profile'), ] Here is my Base.html <ul class="navbar-nav ml-auto"> {% if not user.is_authenticated %} <li class="nav-item"> <a class="nav-link navaour" href="{% url 'register' %}"><i class="fa fa-check-square-o"></i>&nbsp; Sign up Free</a> </li> <li class="nav-item"> <a class="nav-link navaour" href="{% url 'login' %}"><i class="fa fa-user"></i>&nbsp; Login</a> </li> {% else %} <li class="nav-item"> <a class="nav-link navaour" href=""><i class="fa fa-user"></i>&nbsp; Profile</a> </li> <li class="nav-item"> <a class="nav-link navaour" href="{% url 'logout' %}"><i class="fa fa-power-off"></i>&nbsp; Logout</a> </li> {% endif %} Here is my profile_detail_view.html <div class="row"> <div class="col-sm-3 col-md-2 col-5"> <label style="font-weight:bold;">Full Name</label> </div> <div class="col-md-8 col-6"> {{user.username}} </div> </div> Any Help Appreciated Thanks! -
django.db.utils.OperationalError: (1044, "Access denied for user 'someuser'@'localhost' to database '/path/to/Database"')
There are a few questions like this on this site but none have answered my problem specifically. I have tried dropping all users and databases and re-creating. I have granted all privileges to my user. I have made sure my settings.py includes the correct setup... for the record here is what I have: DIR_FOR_DB = '/path/to/' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': DIR_FOR_DB+ 'Database', 'USER': 'someuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } I can't think of any reason why it's not letting me in. -
Unable to send request.data and get api response?
Requesting with Axios to fetch data from API export const getReports = async (url, obj) => { return new Promise( async (resolve, reject) => { try { const data = await axios.request( { method: 'get', url: BASE_URL+url, headers: { 'Authorization': `Bearer ${await getAccessToken()}` }, data: {date_to:'2019-11-05',date_from:'2019-11-05',c_name:'1'} } ); resolve(data); } catch (e) { reject(e) } } ) }; Getting error and not able to receive request.data on the backend... Working on Postman in Body - date_to:'2019-11-05' -date_from:'2019-11-05' -c_name:'1' -
How to manage django model relations properly?
Here I am making some tour package system.A package will have gallery.And of course gallery will have multiple images so I decided to use ManyToOne relation here.But I also thought of using OneToOne relation between these two models because we can upload multiple images at once through django forms. So what relation would be best here ? class TourPackage(models.Model): name = models.CharField(max_length=255) package_start_date = models.DateTimeField() price = models.FloatField(default=0.0) facilities = models.TextField() class PackageGallery(models.Model): package = models.ForeignKey(TourPackage,on_delete=models.CASCADE) images = models.ImageField(upload_to='gallery') -
Create default related objects when instantiating model
Given two abstract models A and B: class A(models.Model): title = models.Field(...) ... And: class B(models.Model): a = models.ForeignKey(A, ...) ... How to create a set of related objects of model B every time new record of model A is created? At the moment the most straight-forward approach seems to be using: @receiver(models.signals.post_save, sender=A) def create_default_b_objects(sender, instance, created, **kwargs): if created: #create related instances of model B ... But maybe there's more elegant way by using data migrations or fixtures described in django documentation? -
Deserialization to specific object based on field value in djnago
Right now I have an object model: class Report(models.Model): TYPE1 = 'type1' TYPE2 = 'type2' TYPES_CHOICES = [ (TYPE1, 'type1'), (TYPE2, 'type2'), ] name = models.CharField(max_length=255) type = models.CharField(max_length=20, choices=TYPES_CHOICES) and ModelSerializer which corresponds to this model: class ReportSerializer(serializers.ModelSerializer): class Meta: model = Report depth = 1 fields = ('name', 'type') Basing on type value I would like to create Type1Report or Type2Report (they will implement some methods in another way). But both Type1Report and Type2Report should be saved in the same database table. Is there a way to do it with the use of the DRF serializer and without walkarounds? If there is no such a way what is the best practice to do so? -
Need Help in Django Deployment
I want help in deploying my django app. i tried deploying on heroku but its giving me alot of errors. like: SECRET_KEY must not be empty(even if its not empty) APP_CRASHED i've tried hosting on pythonanywhere too but it gives me errors as well. also, i'm using postgres as database. my github repo: https://github.com/HooriaHIC/Xannys 2019-11-12T10:52:11.710011+00:00 app[web.1]: worker.init_process() 2019-11-12T10:52:11.710014+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process 2019-11-12T10:52:11.710016+00:00 app[web.1]: self.load_wsgi() 2019-11-12T10:52:11.710018+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2019-11-12T10:52:11.710020+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2019-11-12T10:52:11.710026+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2019-11-12T10:52:11.710028+00:00 app[web.1]: self.callable = self.load() 2019-11-12T10:52:11.710030+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2019-11-12T10:52:11.710032+00:00 app[web.1]: return self.load_wsgiapp() 2019-11-12T10:52:11.710034+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2019-11-12T10:52:11.710036+00:00 app[web.1]: return util.import_app(self.app_uri) 2019-11-12T10:52:11.710038+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app 2019-11-12T10:52:11.710040+00:00 app[web.1]: __import__(module) 2019-11-12T10:52:11.710046+00:00 app[web.1]: File "/app/djecommerce/wsgi.py", line 5, in <module> 2019-11-12T10:52:11.710048+00:00 app[web.1]: application = get_wsgi_application() 2019-11-12T10:52:11.710050+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2019-11-12T10:52:11.710052+00:00 app[web.1]: django.setup(set_prefix=False) 2019-11-12T10:52:11.710054+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/__init__.py", line 19, in setup 2019-11-12T10:52:11.710056+00:00 app[web.1]: configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) 2019-11-12T10:52:11.710058+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 79, in __getattr__ 2019-11-12T10:52:11.710060+00:00 app[web.1]: self._setup(name) 2019-11-12T10:52:11.710062+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 66, in _setup 2019-11-12T10:52:11.710063+00:00 app[web.1]: self._wrapped = Settings(settings_module) 2019-11-12T10:52:11.710065+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 176, in __init__ 2019-11-12T10:52:11.710068+00:00 app[web.1]: raise … -
How can I ignore unknown arguments passed as inputs to a mutation?
As per the GraphQL spec https://graphql.github.io/graphql-spec/draft/#sec-Input-Objects the input object literal or unordered map must not contain any entries with names not defined by a field of this input object type, otherwise an error must be thrown. Let's say I have a project which has a user called buyer, the schema for which is as follows type Buyer { id: ID! name: String! address: String! email: String! } Now I can write a graphene schema for it class BuyerType(DjangoObjectType): class Meta: model = Buyer and make a mutation for this class BuyerInput(graphene.InputObjectType): name = graphene.String(required=False, default_value='') address = graphene.String(required=False, default_value='') email = graphene.String(required=False, default_value='') class BuyerMutation(graphene.Mutation): """ API to create applicant """ class Arguments: buyer_data = BuyerInput(required=True) buyer = graphene.Field(BuyerType) ok = graphene.Boolean() def mutate(self, info, buyer_data=None): buyer = Buyer(name=buyer.name, address=buyer.address, email=buyer.email) buyer.save() return BuyerMutation(buyer=buyer, ok=True) and write the resolvers functions and query and mutation class. Pretty basic stuff so far. And now to create a new buyer, I just call the mutation mutation { createBuyer( name: "New Buyer" address: "Earth" email: "abc@example.com" ) { ok } } But if I pass an additional field called phone mutation { createBuyer( name: "New Buyer" address: "Earth" email: "abc@example.com" phone: 8541345474 ) { … -
WebDriverException: Message: invalid argument: can't kill an exited process only with Apache
If I run the application using python manage.py runserver the following code launch firefox driver =webdriver.Firefox(firefox_binary, firefox_options=firefoxOptions,log_path='/home/projcts/geckodriver.log') but if I wanted to use Apache the application run without any problem except that it doesn't launch firefox browser. Is it a problem of permissions? or selenium doesn't work with apache? I will appreciate any suggestions -
ValueError at / The 'video_image' attribute has no file associated with it
my model: class News(models.Model): CATEGORY=(("0","Politics"),("1","Sports"),("2","Health"),("3","Business"),("4","International"),("5","Finance")) title=models.CharField(max_length=250) story= models.TextField() count= models.IntegerField(default=0) like = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True , related_name='post_likes') video_url = models.URLField(max_length=270,null=True,blank=True) #makemigrations garna baki xa category= models.CharField(choices=CATEGORY, max_length=2) slug=models.SlugField(max_length=270,blank=True,null=True) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) cover_image=models.ImageField(upload_to="uploads") author= models.CharField(max_length=100,null=True) video_image = models.ImageField(upload_to="uploads",blank=True,null=True) video_title = models.CharField(max_length=250,blank=True,null=True) my view: class NewsTemplateView(TemplateView): template_name="index.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) news=News.objects.all() context["latest_news"] = news.order_by("-created_at") [:4] context["breaking_news"] = news.filter(Q(category="0")|Q(category="1")).order_by("-created_at") [:3] context["political_news"] = news.filter(category="0").order_by("-created_at") [:4] context["sports_news"] = news.filter(category="1").order_by("-created_at") [:4] context["health_news"] = news.filter(category="2").order_by("-created_at") [:4] context["business_news"] = news.filter(category="3").order_by("-created_at") [:4] context["international_news"] = news.filter(category="4").order_by("-created_at") [:4] context["finance_news"] = news.filter(category="5").order_by("-created_at") [:4] context["video_news"] = news.order_by("-created_at") [:3] context["popular_news"] = news.order_by("-count")[:6] return context my template: <!-- Single Video Post --> {% for news in video_news %} <div class="col-12 col-sm-6 col-md-4"> <div class="single-video-post"> <img src="{{ news.video_image.url }}" alt=""> <!-- Video Button --> <div class="videobtn"> <a href="{{news.video_url}}" class="videoPlayer"><i class="fa fa-play" aria-hidden="true"></i></a> </div> </div> </div> {% endfor %} -
How To Make User Profile In Django?
How To Make User Profile in Django? Hi I Want to Know How To Make User Profile when user signup our django app create a profile page for the person and he can share the link to person -
How to access multi-item index model in Views of Django?
I have a Django model with a 3 item index. class Url(models.Model): word1 = models.CharField(max_length=50) word2 = models.CharField(max_length=50) word3 = models.CharField(max_length=50) #more fields here class Meta: indexes= [models.Index(fields=['word1','word2','word3'])] This item is called by a url that contains the index values in my url.py (I think I did this right, still sorta a noobie with django) urlpatterns = [ path('', views.HomeView.as_view()), path('<str:word1>.<str:word2>.<str:word3>',views.redirect) ] But how do I actually load the individual model from my database into my view function for a multi-index entry? def redirect(request,word1,word2,word3): # just load one db entry instead of url = Url.objects.all() return HttpResponseRedirect('someother.variablefrom.mymodel') -
Checking if objects exists and manually raising an error if it doesn't
I need to check if an object exists in a table,if doesn't raise an error and save it to the django cronjoblog table automatically. here's a code that partially does what I want, but it doesnt raise an error an save it to the cronjoblog table: from django.core.exceptions import ObjectDoesNotExist some_object= Some_object.objects.filter(active=True) try: some_object.get() except ObjectDoesNotExist: print("Either the entry or blog doesn't exist.") I need something like: some_object= Some_object.objects.filter(active=True) if not some_object: raise ObjectDoesNotExist("Either the entry or blog doesn't exist.") -
How to make a new serializer class using few fields of two serializers
I have two models, say model1 and model2. I also have two serializer classes namely ModelOneSerializer and ModelTwoSerializer for both of them. I would like to create a new serializer class ( with a new model) using few fields from both of the models ( tables). Now, both of the models have few fields with same name like 'name' , 'capacity' etc. I'd like to use field 'name' from both the models but 'capacity' from the second model. How can I write this new serializer class using few fields from both of the models? -
efficient way of writing a python function
def getObj(self, x,y,z): sheet = self.sheet is_flag = sheet[FLAGTYPE] if is_flag: lines = adlines.objects.filter( key="", msc_cd=adlines.op, tid=x, svc_beg_dt__gte=datera.start, svc_beg_dt__lte=datera.end ).exclude(ind='Y') else: lines = adlines.objects.filter( key="", msc_cd=adlines.op, pid=x, svc_beg_dt__gte=datera.start, svc_beg_dt__lte=datera.end ).exclude(ind='Y') Above code is a part of the function. I have a flag assigned it to a variable and based on flag condition the filter operation happens. is there an efficient way of writing it ? -
Is there a way to get data from tables which contain same foreign key?
I have database with multiple tables. In one of them is model named project which is then used as a foreign key on multiple other models, which are then used as a foreign key themselfs. I am wondering if there is a way (library or command) to get all models which are connected with the top most model (project) in form of command line command or line of code. I have tried with django-fixture-magic, but that is not what I am looking for. -
Django Foreign key constraint error on submitting a row
I just created a Django Project and added 2 directly in mysql: 1) Financial Holdings (tbl_holdings) 2) Service Providers (tbl_holdings_service_providers) Both of their Data Definitions in My Sql are: tbl_holdings CREATE TABLE `tbl_holdings` ( `id` int(11) NOT NULL AUTO_INCREMENT, `item_code` varchar(5) NOT NULL, `product_name` varchar(45) NOT NULL, `service_provider` varchar(100) NOT NULL, `account_details` varchar(100) NOT NULL, `purchase_cost` int(15) NOT NULL, `current_value` int(15) NOT NULL, `purchase_date` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `item_code_UNIQUE` (`item_code`), KEY `fk_service_provider_name_idx` (`service_provider`), CONSTRAINT `fk_service_provider` FOREIGN KEY (`service_provider`) REFERENCES `tbl_holdings_service_providers` (`provider_name`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1 tbl_holdings_service_providers CREATE TABLE `tbl_holdings_service_providers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `provider_name` varchar(100) NOT NULL, `updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `INDEX` (`provider_name`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1 I created the related model in Django models.py class TblHoldings(models.Model): item_code = models.CharField(unique=True, max_length=5) product_name = models.CharField(max_length=45) service_provider = models.ForeignKey('TblHoldingsServiceProviders', models.DO_NOTHING, related_name='service_provider',db_column='service_provider') account_details = models.CharField(max_length=100) purchase_cost = models.IntegerField() current_value = models.IntegerField() purchase_date = models.DateTimeField(blank=True, null=True) updated_at = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True) class Meta: verbose_name = 'Holding' verbose_name_plural = … -
Disable logging in gunicorn with Django for a specific request/URL/point
This question is similar to Disable logging in gunicorn for a specific request / URL / endpoint except that my question is concerned with disabling gunicorn healthcheck logging in a Django app. How do I disable gunicorn logging in a Django app? I'm also using syslog, so the settings.LOGGING dictionary is something like this: LOGGING = { "version": 1, "disable_existing_loggers": False, "handlers": { "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "default", }, "syslog": { "level": "DEBUG", "class": "logging.handlers.SysLogHandler", "formatter": "default", "facility": SysLogHandler.LOG_LOCAL2, "address": syslog_address, }, }, "loggers": { "django": {"handlers": ["console", "syslog"], "propagate": True}, "apps": {"handlers": ["console", "syslog"], "level": "DEBUG"}, "utils": {"handlers": ["console", "syslog"], "level": "DEBUG"}, "gunicorn.access": {"handlers": ["console", "syslog"], "level": "INFO"}, "gunicorn.error": {"handlers": ["console", "syslog"], "level": "INFO"}, }, } Note that I explicitly added the gunicorn.access logger for use with syslog (see: https://github.com/benoitc/gunicorn/issues/2016). -
How to send a post request from Reactjs frontend to django rest framework API, with nested object and file
I try to submit data with object and file. I tested my API, my api in work correctly. But I see error when I send data from the frontend. the error is 400 bad request. people is not exist. This is the format of my api. # this is my model class People(models.Model): name = models.CharField(max_length=255) image = models.FileField(upload_to='people/', null=True, blank=True) def __str__(self): return self.name class Category(models.Model): people = models.ForeignKey(People, on_delete=models.CASCADE) category_name = models.CharField(max_length=255) category_image = models.FileField(upload_to='category_image', null=True, blank=True) def __str__(self): return self.category_name # this is my serializer class PeopleSerializer(serializers.ModelSerializer): class Meta: model = models.People fields = ('id', 'name', 'image') class CategorySerializer(serializers.ModelSerializer): people = PeopleSerializer() class Meta: model = models.Category fields = ('id', 'people', 'category_name', 'category_image') def create(self, validated_data): people_data = validated_data.pop('people') people = models.People.objects.create(**people_data) category = models.Category.objects.create(people=people, **validated_data) return category # This is the view class PeopleViewSet(viewsets.ModelViewSet): serializer_class = serializers.PeopleSerializer queryset = models.People.objects.all() class CategoryViewSet(viewsets.ModelViewSet): serializer_class = serializers.CategorySerializer queryset = models.Category.objects.all() `import React, {Component} from 'react'; import axios from "axios"; class AddPeople extends Component { state = { name: '', image: null, category_name: '', category_image: null, }; handleChange = (e) => { this.setState({ [e.target.id]: e.target.value }) }; handleImageChange = (e) => { this.setState({ image: e.target.files[0], category_image: e.target.files[0] }) }; … -
Update after a delete with Vue.JS, Django REST
I am testing the functioning of VueJS and Django REST. For the moment I can display the data stored in REST and modify them. I can also delete them but I have to reload the page to see the deletion. I would like the line in the table that is deleted to be done without reloading the page. Can you help me? <script> export default { data () { return { users: [], } }, mounted () { this.$user = this.$resource('"APIaddress"/prescripteur{/id}/') this.$user.query().then((response) => { this.users = response.data },(response) => { console.log('erreur', response) }) }, methods: { create (user) { }, save (user) { this.$user.update({id: user.id}, { nom: user.nom, prenom: user.prenom, adresse1: user.adresse1, cp: user.cp, ville: user.ville, specialite: user.specialite, civilite: user.civilite }).then((response) => { }, (response) => { console.log('erreur', response) }) }, destroy (user) { this.$user.remove({id: user.id}).then((response) => { }, (response) => { console.log('erreur', response) }) } } } </script> I tried to add that: updated () { this.$user = this.$resource('"APIaddress"/prescripteur{/id}/') this.$user.query().then((response) => { this.users = response.data },(response) => { console.log('erreur', response) }) }, But the recharging is done continuously and I can no longer modify the fields but the deletion is done.