Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django class based views- handle redirect to the same view, add new context
After POST request I want to redirect user to the same view, adding something to the context. I have no idea how to do it. I tried using get_context_data(**kwargs) but I think I don't really understand the concept. If I do not add anything into context I simply redirect to the same view, which sounds dumb but works. Here's my code: (the class is "home.html" view) class FilteredZamTableView(LoginRequiredMixin, SingleTableMixin, FilterView): table_class = ZamTable template_name = 'home.html' paginate_by = 10 filterset_class = ZamFilter def post(self, request, *args, **kwargs): if request.POST.get('accept_zam'): try: ... return redirect('home') except Exception as e_msg: context = self.get_context_data(**kwargs) context['error'] = e_msg return render(response, "home.html", context) I get this error msg at self.get_context_data(**kwargs) django.urls.exceptions.NoReverseMatch: Reverse for 'home' with keyword arguments '{'e_msg': AttributeError("'FilteredZamTableView' object has no attribute 'object_list'")}' not found. 1 pattern(s) tried: ['$'] -
Marshmallow didn't serialize nested one-to-many Django relation
I need to serialize list of Post objects and return it as JSON in Django. For this purpose I use marshmallow. It works fine, except nested Comment model, that not serializing at all: [ { "id": 6, "created_at": "2021-03-22T13:57:24.576260+00:00", "user": { "id": 1, "username": "admin" }, "group": { "title": "Post title", "id": 2, "members": 6 }, "text": "This is post text" } ] And it should be like this: [ { "id": 6, "created_at": "2021-03-22T13:57:24.576260+00:00", "user": { "id": 1, "username": "admin" }, "group": { "title": "Post title", "id": 2, "members": 6 }, "comments": { { "id": 1, "user": { "id": 1, "username": "admin" }, "text": "This is first comment text" }, { "id": 2, "user": { "id": 1, "username": "admin" }, "text": "This is second comment text" } }, "text": "This is post text" } ] Here is a code. Models: class Post(models.Model): text = models.TextField(max_length=1600) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True,) group = models.ForeignKey(Group, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.CharField(max_length=1200) created_at = models.DateTimeField(auto_now_add=True) Marshmellow schema: class CommentSchema(Schema): id = fields.Int() user = fields.Nested(UserSchema) text = fields.Str() class PostSchema(Schema): id = fields.Int() text = fields.Str() created_at = fields.DateTime() user … -
Nepali Date-picker orientation/placement required to top
I'm using NepaliDatepicker from here: https://leapfrogtechnology.github.io/nepali-date-picker/demo/ i attached datepicker placed at the bottom of the popup page. My problem is that the datepicker appears below the screen. when when i reduce zoom only then i see this else not. -
How is the UserAttributeSimilarityValidator supposed to be used in Django?
I am testing a REST API I wrote in Django, but this validator does not work as intended. I read the docs on this, but I need more than a description; I need a working example. I have it defined in settings.py as is the default. # my_app/settings.py AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, ... ] However, when I run the test, I get an unexpected and undesired success. # api/authentication/tests.py body = { 'username': 'frank', 'email': 'frank@example.com', 'password1': 'frank@example.com', 'password2': 'frank@example.com', } response = self.client.post(url, body, format='json')) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) > ./manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_register (api.authentication.tests.AuthTests) Ensure we can register a user and test for validation errors. ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/matt/Repositories/my_app/back-end/api/authentication/tests.py", line 108, in case_password_has_email self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) AssertionError: 201 != 400 ---------------------------------------------------------------------- Ran 1 test in 0.275s FAILED (failures=1) Destroying test database for alias 'default'... Am I missing the point of this validator? Am I just using it wrong? My intended behavior is for a 400 response to be sent with an error message, like the other validators allow for. How do I accomplish this? -
String value for decimal field doesn't throw ValidationError in view but works fine in shell
I created test project to figure this out. Here is the form: class PaymentForm(forms.Form): amount = forms.DecimalField(max_digits=2, decimal_places=2, required=False) Everything works as expected in shell: >>> from testapp.forms import PaymentForm >>> f = PaymentForm({'amount': 'a'}) >>> f.errors {'amount': ['Enter a number.']} >>> f.is_valid() False But if I enter string value in a template and submit the form, it doesn't give any error messages at all and 'it is valid' is being printed. def add_payment(request): if request.method == 'POST': payment_form = PaymentForm(request.POST) if payment_form.is_valid(): print('it is valid') else: payment_form = PaymentForm() return render(request, 'testapp/add.html', {'payment_form': payment_form}) When i make the field required, the form gives the expected 'Enter a number' and the view - 'Required field' error message. Any ideas how to make it work? Is this how django forms supposed to work? Because i couldn't find anything by googling. -
Filter two models django
I have two similar models: class Boat(models.Model) name = models.CharField(max_length=140, help_text="Enter a Boat name") company = models.CharField(max_length=140) time = models.TimeField(auto_now=False, auto_now_add=True, editable=False, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ['-time'] class Car(models.Model) name = models.CharField(max_length=140, help_text="Enter a Boat name") company = models.CharField(max_length=140) time = models.TimeField(auto_now=False, auto_now_add=True, editable=False, blank=True, null=True) def __str__(self): return self.name class Meta: ordering = ['-time'] For example, there are 3 objects of the car model: Name Created Nissan Almera 02/2/2020 Renault Logan 01/9/2020 Mitsubishi L200 03/24/2021 and 1 one object of the boat model: Name Created wooden boat 01/01/2021 Is it possible to make a filter that would display the 3 most recently created objects? i.e wooden boat, mitsubishi L200 and renault Logan -
defining all columns in django values just to get foreign key value
I am working on a Django app and I have a model containing about 60 columns with few ForeignKeys For e.g. class Company(models.Model): name = models.CharField(max_length=100) city = models.CharField(max_length=100) address = models.CharField(max_length=100) user = models.ForeignKey(User, on_delete=models.CASCADE) # and many more rows I need to show all data in DataTable. Company.objects.all().values() To get the username from user column, I need to call it as Company.objects.all().values('user__username') But this doesn't makes sense to me, Just to get the username, I will have to define all columns of Company model Company.objects.all().values('name', 'city', 'address', 'user__username') I was already getting 'name', 'city', 'address' with .values() But to get username, I have to define them explicitly. This is okay with small models, but this approach becomes tidious and error-prone with bigger models. I'm sure there must be a better way to do this that I dont know. Any help would be appreciated. -
Django query sets optimization
I am having a function with some filtering logic, and returns certain levels after passing through different validations, however I would like to optimize this code so that I remove duplicates from the querysets. Its not that direct , but it's possible to see the duplicates, how best can I remove the duplicates below : def get_bo_level(self, main_company): shares = BeneficialOwnerShares.objects.filter( parent_company=self, owner_company=main_company) if shares.exists(): return 1 level_one_business = BeneficialOwnerShares.objects.filter( parent_company=self).values_list('owner_company') shares = BeneficialOwnerShares.objects.filter( parent_company__in=level_one_business, owner_company=main_company) if shares.exists(): return 2 parents = BeneficialOwnerShares.objects.filter( owner_company=self ).values_list('parent_company', flat=True) level_three_business = BeneficialOwnerShares.objects.filter( owner_company__in=parents, parent_company=main_company ).first() if level_three_business: return 3 return None -
CORS allowing jsonplaceholder
I'm learning vue and I'm experimenting with API calls with axios to my local django server. Therefore I encountered CORS errors. I already know how CORS works and why it is blocking my calls, however when I try to send a call to this fake API for testing, it works flawlessly. How is cors allowing it? Here's an example code: axios.get('https://localhost:8000/api/posts') .then( () => console.log('Local server working :)')) axios.get('https://jsonplaceholder.typicode.com/todos') .then( () => console.log('Fake api working :)')) Result: -
How retrieve Discord messages to my website?
I currently have a Python/Django platform and a Discord community. I would like to get the messages of a channel to convert them into notifications on the site. Obviously I consulted the Discord doc but I really have trouble understanding. I don't want to create a bot for this simple action, in principle by using the OAuth app with the "messages.read" scopes it would be possible. I can generate my token now: def discord_get_token(): data = { 'client_id':DISCORD_CLIENT_ID, 'client_secret':DISCORD_PRIVATE_KEY, 'grant_type': 'client_credentials', 'redirect_uri': 'http://127.0.0.1:8000', 'scope': 'identify connections messages.read' } headers = { 'Content-Type': 'application/x-www-form-urlencoded' } r = requests.post('%s/oauth2/token' % DISCORD_BASE_URI, data=data, headers=headers) r.raise_for_status() #Token print(r.json()['access_token']) return r.json()['access_token'] Then the call to the messages with the following route /channels/{channel.id}/messages : def get_channel_messages(id_channel): route = "/channels/"+ str(id_channel) +"/messages" data,error_message = request_discord('GET',route) print(data) def request_discord(method,url_access,body={}): data ='' #Call token error_message = '' access_token = discord_get_token() #Call request headers = {'Content-Type':'application/json','Authorization':'bearer ' + access_token} body = body if method=="GET": result = requests.get(DISCORD_BASE_URI + url_access, headers=headers,data=body) else: result = requests.post(DISCORD_BASE_URI + url_access, headers=headers,data=body) #Check result if result.status_code != 200 and result.status_code != 201: error_message = "Impossible de d'obtenir un resultat erreur: " + str(result.status_code) else: data = result.json() return data,error_message A 401 error is returned. Unlike … -
Stop Celery Job to get triggered at every deployment on AWS
I am usingCelery in Docker container deployed on AWS for some asynchronous jobs scheduling withRedis as the broker. Here is my config in settings.py. All is working well. My only issue is the the job is getting triggered at every deployment even though I have set specific times for it. Otherwise after the deployment it works fine. I am scratching my head to stop the first triggering. settings.py CELERY_BROKER_URL = "redis://localhost:6379" CELERY_RESULT_BACKEND = "redis://localhost:6379" CELERY_BEAT_SCHEDULE = { "fill_db_daily": { "task": "agendanotification.tasks.fill_db_daily", "schedule": crontab(hour=0, minute=1), }, "articles_email_daily": { "task": "agendanotification.tasks.articles_email_daily_prod", "schedule": crontab(hour=0, minute=30), } } In tasks.py: @shared_task def fill_db_daily(): call_command("fill_db", ) @shared_task def articles_email_daily_prod(): call_command("articles_email_prod", ) -
500 error when deploying Django app to Heroku with no obvious error messages
I am trying to deploy my Django app via Heroku and keep receiving a 500 error. I'm new to Django so am not really sure what could be going wrong as I've followed a tutorial online pretty closely, but I've obviously mucked something up somewhere. I've looked at the logs and it doesn't really tell me anything... at least nothing that I can decipher. Thanks to anyone who's able to translate this into English. 2021-03-24T11:09:44.413513+00:00 heroku[web.1]: State changed from starting to up 2021-03-24T11:09:47.222339+00:00 heroku[router]: at=info method=GET path="/" host=thediamondseeker-2.herokuapp.com request_id=19a272b0-7efa-43d5-bbd1-8e28a70cb43a fwd="94.1.111.13" dyno=web.1 connect=1ms service=985ms status=500 bytes=410 protocol=https 2021-03-24T11:09:47.218908+00:00 app[web.1]: 10.29.126.3 - - [24/Mar/2021:11:09:47 +0000] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36" This is my settings.py """ Django settings for diamonds project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production … -
Authorization Headers is missing using c# client
I am developing a RESTFUL API using django-rest-framework. And for Authorization I choose to use Token Authorization (not JWT). Below is what I tried: Using POSTMAN (Works) headers: Authorization: Token 329367424fd30a876ccff05dbc5a18d86fe7158c Using C# Client (no working) HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", "Token 329367424fd30a876ccff05dbc5a18d86fe7158c"); await client.GetAsync(<url>) // Authentication credentials were not provided. After I debug and override TokenAuthentication function, I realize that Authorization headers is being removed if requested from C# Client. I saw a lot of question are being asked related to this problem, and the solution is adding WSGIPassAuthorization On I am not sure where should I add above line wsgi.py import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nusames_core.settings') application = get_wsgi_application() FYI: I am planning to use gunicorn as my webserver, also I need it work locally (I am not using venv) Question: is there any workaround for my local env in order to make it works on c# client, and is there any best practice for production env? -
AttendanceRange matching query does not exist in django
Traceback (most recent call last): File "D:\Apps\Python\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Apps\Python\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "D:\Apps\Python\lib\site-pack`enter code here`ages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) File "D:\Apps\Python\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1581, in _changeform_view self.save_related(request, form, formsets, not add) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1121, in save_related self.save_formset(request, form, formset, change=change) File "D:\Apps\Python\lib\site-packages\django\contrib\admin\options.py", line 1109, in save_formset formset.save() File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 673, in save return self.save_existing_objects(commit) + self.save_new_objects(commit) File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 811, in save_new_objects self.new_objects.append(self.save_new(form, commit=commit)) File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 951, in save_new return super().save_new(form, commit=commit) File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 650, in save_new return form.save(commit=commit) File "D:\Apps\Python\lib\site-packages\django\forms\models.py", line 460, in save self.instance.save() File "D:\Apps\Python\lib\site-packages\django\db\models\base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "D:\Apps\Python\lib\site-packages\django\db\models\base.py", line 801, in save_base post_save.send( File "D:\Apps\Python\lib\site-packages\django\dispatch\dispatcher.py", line 177, in … -
Embedded Google Analytics API but not showing property and views and other data
I have embedded google analytics API using https://developers.google.com/analytics/devguides/reporting/embed/v1/getting-started. I am testing it on localhost, I have successfully embedded the GA API but it is not populating any data. plz check the image -
Checking if the .csv file is formatted correctly before importing to avoid embedding wrong data into database
I am working on a django project that requires updating database with bulk data provided in an excelsheet format. So basically, a user can upload a .csv file if it is in a correct format. I know how to import a file using django-import-export, but the problem is , i don't know how to perform checks like checking if the .csv file has correct column names and information before updating database. I am new to django, please help. -
Django model formset is not saving data to backend db
I am trying to save data using modelformset_factory but i am unavle to do so, i am wondering why? Here is my views.py views.py if request.POST: try: user_info = Education.objects.filter(applicantt= applicant_info).first() formset = educationformset(request.POST, instance=user_info) if formset.is_valid(): print(formset.cleaned_data) for form in formset: obj = form.save(commit=False) obj.id = user_info obj.applicantt = applicant_info obj.save() return redirect('test') else: context['education_form'] = formset except: formset = educationformset(request.POST) if formset.is_valid(): for form in formset: obj = form.save(commit=False) obj.applicantt = applicant_info obj.save() return redirect('test') else: context['education_form'] = formset This the template i am using.... template <form method="POST" class="">{% csrf_token %} {{ education_form.management_form}} {% for form in education_form %} <table class="table table-bordered" cellspacing="0" > <thead id="head"> <tr> {% for field in form.visible_fields %} <th >{{field.label}}</th> {% endfor %} </tr> </thead> <tbody id="head"> <tr > {% for field in form.visible_fields %} <th>{{field}}</th> {% if error in field.errors %} <small id="" class="text-danger"> {{error}} </small> {% endif %} {% endfor %} </tr> </tbody> </table> {% endfor %} <div class="card-block"> <button type="submit" class="btn btn-success center-block pull-right" href="{% url 'test' %}">Finish</button> </div> </form> and finally this is my model.py which i am using for the project.... models.py class Education(models.Model): LEVEL = [ ('Matric','Matric'), ('Intermediate','Intermediate'), ('Graduation','Graduation'), ('Master','Master'), ('Doctrate','Doctrate'), ] applicantt = models.ForeignKey(Personal, on_delete=models.CASCADE, unique=False) … -
How to add data to different table using signals?
In my invoicing app, when client make payment, i create new clientpayment with date and client name and amount paid, and in clientpaymentitem i choose one or many invoices that client paid and put the amount_paid on each line and where the money is stored, in bank or cashier. i can receive cash and check for example and then i select treasury.cashier for invoice paid on cash and the other paid with check same way treasury.bank. now i want when i save the clientpayment that this transaction will be saved on treasury on same time, no need to repeate the whole things. I tried to use signals but didn't work correctly for me in case i modify the amount for ex. class ClientPayment(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey('Client',on_delete=models.PROTECT) total_paid = models.DecimalField(default=0, max_digits=20, blank=True, null=True, decimal_places=2) class ClientPaymentItem(models.Model): clientpayment = models.ForeignKey('ClientPayment', on_delete=models.CASCADE) invoice = models.ForeignKey('Invoice', on_delete=models.PROTECT) amount_paid = models.DecimalField(max_digits=20, decimal_places=2) treasury = models.ForeignKey('Treasury', on_delete=models.PROTECT) class Treasury(models.Model): name = models.CharField(max_length=256) class TreasuryItem(models.Model): treasury = models.ForeignKey('Treasury', on_delete=models.CASCADE) date = models.DateField(default=timezone.now) name = models.CharField(max_length=256) debit = models.DecimalField(max_digits=20, decimal_places=2, default=0) credit = models.DecimalField(max_digits=20, decimal_places=2, default=0) -
Django: TypeError: post() missing 1 required positional argument: 'request'
I am getting below error when I pass the invalid credentials. TypeError: post() missing 1 required positional argument: 'request' I don't understand it. Here is the view. View: class LogInView(TemplateView): template_name = "login.html" @staticmethod def post(self, request, *args, **kwargs): username_or_email = request.POST['username'] password = request.POST['password'] if '@' in username_or_email: username = User.objects.get(email=username_or_email).username else: username = username_or_email if username and password: user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect('/admin') else: messages.warning(request, 'Sorry, wrong username or password.') return render(request, self.template_name) else: messages.warning(request, 'Username and Password cannot be blank.') return render(request, self.template_name) Here is the url. Url: from django.urls import path, include from sa.views import ( LandingPageView, LogInView, LogOutView, ) urlpatterns = [ path('', LandingPageView.as_view(), name='LandingPageView'), path('login', LogInView.as_view(), name='LogInView'), path('logout', LogOutView.as_view(), name='LogOutView'), ] Please help. -
'tensorflow' has no attribute 'get_default_session'
I am currently working on a project using DJANGO KERAS and TENSORFLOW But I am really facing some issues while executing the project I even reinstalled DJANGO KERAS and TENSORFLOW but I still face these issues I have also added the screenshots of the error message Please help me to solve the issueenter image description here [Command Prompt][Webpage] default_session = tf.get_default_session() AttributeError: module 'tensorflow' has no attribute 'get_default_session' -
How to show breaklines in textarea and data fetch from JavaScript to My inner Text of textarea
I want to get data from user in <textarea> and show it on the DOM page with edit button and with breaklines if user click on edit user old data send to new <textarea> with breaklines Adding an item. <form name="add" method="POST" action="{% url 'notepad:addnote' %}">{% csrf_token %} <div class="modal-body"> Title : <input name="title" class="w-50" type="text" required><br> Note :<br> <textarea name="text" id="" cols="60" rows="10" required></textarea> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save</button> </div> Showing an items. <div id="content"> {% for items in allitems %} <ul class="list-group d-inline-block my-4 "> <li class="list-group-item list-group-item-info list-group-item-action {{items.id}}" aria-current="true">{{items.title}}<button onclick="editContent({{items.id}})" data-bs-toggle="modal" data-bs-target="#update" type="button" class="save mx-2"><i class="fa fa-pencil-square-o"></i></button></li> <li class="list-group-item list-group-item-action {{items.id}}">{{items.text}}</li> </ul> {% endfor %} </div> But if i show an items it removes break lines. So I'll try pre tag to show that content with breaklines. <div id="content"> {% for items in allitems %} <ul class="list-group d-inline-block my-4 "> <li class="list-group-item list-group-item-info list-group-item-action {{items.id}}" aria-current="true">{{items.title}}<button onclick="editContent({{items.id}})" data-bs-toggle="modal" data-bs-target="#update" type="button" class="save mx-2"><i class="fa fa-pencil-square-o"></i></button></li> <pre><li class="list-group-item list-group-item-action {{items.id}}">{{items.text}}</li></pre> </ul> {% endfor %} </div> It shows break lines, but i again want to edit and send this content to my input and textarea to edit that's content , So i … -
Direct assignment to the forward side of a many-to-many set is prohibited. Use order.set() instead
When i try to post a order i get error saying 'Direct assignment to the forward side of a many-to-many set is prohibited. Use order.set() instead.' Any help would be great. here is my models.py class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) food_item = models.ForeignKey(FoodItem,on_delete=models.CASCADE) quantity = models.IntegerField(default=0,null=True,blank=True) size = models.CharField(max_length=10,choices=SIZE_CHOICES,null=True,blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.quantity} of {self.food_item}' class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) order = models.ManyToManyField(OrderItem,null=True) order_created = models.DateTimeField(auto_now_add=True) paid = models.BooleanField(default=False,null=True,blank=True) transction_id = models.CharField(max_length=30,unique=True,null=True,blank=True) def __str__(self): return self.user.username Here is my serializer.py class OrderItemListSerializer(serializers.ModelSerializer): #user = UserSerializer(many=True,read_only=False) class Meta: model = OrderItem fields = ['id','user','food_item','quantity','size'] def create(self,validated_data): return OrderItem.objects.create(**validated_data) class OrdersSerializer(serializers.ModelSerializer): order = OrderItemListSerializer(many=True,) class Meta: model = Order fields = '__all__' depth = 0 # def create(self, validated_data): def create(self,validated_data): return Order.objects.create(**validated_data) here is my views.py class OrderPost(APIView): # add permission to check if user is authenticated permission_classes = [permissions.AllowAny] # 2. Create def post(self, request, *args, **kwargs): serializer = OrdersSerializer(data=request.data) serializer.set(order) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) error Direct assignment to the forward side of a many-to-many set is prohibited. Use order.set() instead. -
Payments on website: From customers to the website and vice versa
I am creating a website that needs to do this points: Receive payments to the Web site. I know that there are several payments gateways to do this. Can anyone recommend any? Make payments from the Web site to the people who are registered on the site. This people can live in any country and so they can have accounts in any bank of the world. It's possible to make bank transfers to any bank? There's another way to do it, for example with PayPal? If anyone has another idea how to do this I would be very grateful if you tell me. Without having this resolved I cannot move forward on my website. My Web site uses: HTML, CSS, Bootstrap, Jquery, Django y Python, with a SQLLite database. Thanks. -
How can i run a Django app and a Vue on the same port?
I'm building a SPA using Django for my backend and Vue to handle the entire frontend. In order to avoid some security issue and keep using the standard Django's session authentication, i'm going to run these two apps in production on the same sever and on the same port, and i will setup Nginx to route traffic, so that /account/login will be handled by Django, while /app/someURL is redirected to the Vue application. My question is: how can i do the same locally, during development? If i run manage.py runserver and npm run serve -- ---port 8000 the two apps will clash because there is no way to know where should each request be redirected. -
Django multithread database update
how do you guys handle database update when running a multithread? When I call download_image function and perform operation, it hangs after the last line to update Django ImageField for newly created thumbnail, any clue? def main(): with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: for indi_image in all_images_without_thumbnail: executor.submit(download_image, indi_image) def download_image(indi_image): image = Image.objects.get(pk = indi_image_id) image_request_result = requests.get(image.url) img_temp = PilImage.open(BytesIO(image_request_result.content)) width, height = img_temp.size max_size = [200, 200] if width > 200 or height > 200: img_temp.thumbnail(max_size) image_io = BytesIO() img_temp.save(image_io, format='JPEG') filename = image.key.split('/')[-1] file_location = os.path.join(str(image.data_set_id), filename) image.thumbnail.save(file_location, ContentFile(image_io.getvalue()), save=True) print ("here it never reach this line, only hang and no Error or Exception raised")