Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add email to be able to log in via Google oauth Django
I'm building a Django project and I have 3 applications. Students log in to complete the given items. Teachers log in to manage the list of student actions. Administrators manage permissions and logins. Administrators will add student and teacher email addresses. to check that only the added email will be able to log in and my project is using only google oauth login, can anyone guide me what i need to do? If you want an admin to add an email address And only the added email will be able to login. what i tried views.py def admin_user_setting(req): if req.method == "POST": email_user = req.POST.get('email_user') obj = Add_User_Email_User(email_user=email_user) obj.save() return redirect('/admin_user_setting') else: obj = Add_User_Email_User() obj = Add_User_Email_User.objects.all() AllUser = Add_User_Email_User.objects.all() page_num = req.GET.get('page', 1) p = Paginator(AllUser, 10) try: page = p.page(page_num) except: page = p.page(1) context = { "AllUser": Add_User_Email_User.objects.all(), "page" : page, } return render(req, 'pages/admin_user_setting.html', context) urls.py urlpatterns = [ path('admin_user_setting',views.admin_user_setting, name="admin_user_setting"), ] forms.py class UserForm(ModelForm): class Meta: model = Add_User_Email_User fields = ['email_user'] admin.py admin.site.register(Add_User_Email_User) models.py class Add_User_Email_User(models.Model): email_user = models.CharField(max_length=500, null=True) def __str__(self): return self.email_user -
I want to make a subscription system with django
How can I make an auto incrementing timer, for example, it will count forward 1 year from now and these transactions will be saved in the database. -
How to check django login status in JavaScript?
What is the best way to check django user is authenticated in JavaScript file? -
How to implement recursive in Django Serializers
My serializers class class ConditionSerializers(serializers.ModelSerializer): class Meta: model = TblCondition fields = ['id','operator','condition','relation'] class ConditionSerializers(serializers.ModelSerializer): relation_with=ConditionSerializers(many=False) class Meta: model = TblCondition fields = ['id','operator','relation_with','condition','relation'] class RuleSerializers(serializers.ModelSerializer): conditiontbl=ConditionSerializers(many=True) class Meta: model = TblRule fields = ['rule_table_no','rule_no','rule_name','columns','data_file','true','conditiontbl' ] My model class class TblRule(models.Model): rule_table_no=models.AutoField(primary_key=True) rule_no=models.IntegerField(blank=False) rule_name=models.CharField(max_length=100,blank=False) columns=models.CharField(max_length=100) data_file=models.CharField(max_length=100) true=models.CharField(max_length=100) class TblCondition(models.Model): rule=models.ForeignKey(TblRule, on_delete=models.CASCADE,related_name='conditiontbl') operator=models.CharField(max_length=100) condition=models.CharField(max_length=100) relation=models.CharField(max_length=50,blank=True) relation_with=models.OneToOneField(to='self',null=True,blank=True,on_delete=models.CASCADE) Getting these results in postman API by calling ruletbl models [ { "rule_table_no": 2, "rule_no": 1, "rule_name": "Age Discritization", "columns": "Age", "data_file": "Data1", "true": "Teen", "conditiontbl": [ { "id": 4, "operator": ">", "relation_with": null, "condition": "15", "relation": "" }, { "id": 5, "operator": "<=", "relation_with": { "id": 4, "operator": ">", "condition": "15", "relation": "" }, "condition": "25", "relation": "and" } ] }, { "rule_table_no": 3, "rule_no": 1, "rule_name": "Age Discritization", "columns": "Age", "data_file": "Data1", "true": "Young", "conditiontbl": [] } ] You can see conditiontbl list fileds in ruletbl model (e.g. in JASON results), inside conditiontbl filed we have objects of tblcondition models with fileds ("relation_with"), and this relation_with filed is again refering to its own tblcondition model you can see its second object. I want this refering in relation_with fileds to its own conditiontbl model to be recursive. Any solution ? -
Prevent form from resubmitting after button click
I have a Django project where I have a few forms. What is happening is when I click button submit 30 times, my data is inserted 30 times in the database. I did my research and I saw lots of jquery or javascript solutions in general but I am not familiar much with them so I am trying to find a more pythonic/django solution. Here is my code: views: @method_decorator(login_required(login_url='index', redirect_field_name=None), name='dispatch') class CreatePostView(views.FormView): model = Post form_class = CreatePostForm template_name = 'posts/create_post.html' def form_valid(self, form): post = form.save(commit=False) post.user = self.request.user post.save() return redirect('index') template: <form action="{% url 'create post' %}" method="POST" enctype="multipart/form-data"> {{ form.as_p }} {% csrf_token %} <p> <button type="submit" class="btn btn-secondary">Submit</button> </p> </form> model: class Post(models.Model): MAX_TITLE_LENGTH = 20 MIN_TITLE_LENGTH = 3 MAX_DESTINATION_LENGTH = 30 MIN_DESTINATION_LENGTH = 3 MAX_DESCRIPTION_LENGTH = 550 MIN_DESCRIPTION_LENGTH = 5 title = models.CharField( max_length=MAX_TITLE_LENGTH, validators=(MinLengthValidator(MIN_TITLE_LENGTH), name_and_title_validator), error_messages={ 'max_length': f'Post title must be a maximum of {MAX_TITLE_LENGTH} characters.', 'min_length': f'Post title must be at least {MIN_TITLE_LENGTH} characters long.', }, null=False, blank=False, ) photo = CloudinaryField( folder='mediafiles/post_photos', public_id=get_photo_name_by_post_name, null=False, blank=False, ) destination = models.CharField( max_length=MAX_DESTINATION_LENGTH, validators=(MinLengthValidator(MIN_DESTINATION_LENGTH), ), error_messages={ 'max_length': f'Destination must be a maximum of {MAX_DESTINATION_LENGTH} characters.', 'min_length': f'Destination must be at least {MIN_DESTINATION_LENGTH} … -
using tabula with excel data with Django
I have a django application. And I try to format data from excel, But I get this error: Exception Type: ValueError Exception Value: not enough values to unpack (expected 2, got 1) So I have this function: class ExtractingTextFromExcel: def init(self): pass def extract_data_excel_combined(self): dict_fruit = {"Watermeloen": 3588.20, "Appel": 5018.75, "Sinaasappel": 3488.16} # calculate_total_fruit = self.calulate_total_fruit_NorthMidSouth() columns = ["naam fruit", "totaal kosten fruit"] print("\n".join(f"{a} {b:.2f}" for a, b in dict_fruit.items())) return "\n".join( f"{a} {b:.2f}" for a, b in mark_safe( tabulate( dict_fruit.items(), headers=columns, tablefmt="html", stralign="center", ) ) ) then views.py: def test(request): filter_excel = ExtractingTextFromExcel() content_excel = "" content_excel = filter_excel.extract_data_excel_combined() context = {"content_excel": content_excel} return render(request, "main/test.html", context) and template: <div class="form-outline"> <div class="form-group"> <div class="wishlist"> {{ content_excel }} </div> </div> </div> question: how to format data from excel correct with tabula? -
How to simulate a Field storing only hours and minutes in Django
I would like to store for a model "House", in django, a field stocking an hour and a minute, and to be able to edit it easily by only editing hour and minute. I am aware that TimeField exists in django, but its editing in Django admin is not so great : You have to set your value like this : 10:59:00 (for 10:59am) I would like to be able to get a line with : Hour [...] Minute [...] to be able to input two numbers (with validators so that the hour has to be between 0-23 and minutes between 0-59). My best idea at this point was to make a OnetoOneField in the "House" model to an "Hour" Model which get two IntegerField (And using validators). It works great, but the downside is that while editing an instance of House in admin, i can see the Hour instances linked to other instances of House. For exemple if i have two "House" instances, House1 and House2, when i edit House2, i can see the Hour instance linked to House1 in the scrolling menu. (Problem that i would not get if i had directly two IntegerField in "House" for exemple). … -
Getting query length with Ajax / Django
According to the selection in the form, I want to get the number of records that match the id of the selected data as an integer. Here is my view : def loadRelationalForm(request): main_task_id = request.GET.get('main_task_id') relational_tasks = TaskTypeRelations.objects.filter(main_task_type_id = main_task_id) data_len = len(relational_tasks) return JsonResponse({'data': data_len}) Here is my ajax : <script> $("#id_user_task-0-task_types_id").change(function () { const url = $("#usertask-form").attr("data-relationalform-url"); const mainTaskId = $(this).val(); $.ajax({ url: url, data: { 'main_task_id': mainTaskId, }, success: function (resp) { console.log(resp.data); } }); }); I want to write the number of relational tasks associated with the main_task_id of the selected data in the form. But I couldn't do it. Thanks for your help. Kind regards -
ModuleNotFoundError: No module named 'myapp.urls'
I tried to change setting to below but doesn't work: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp'] my directory: manage.py django_project __init__.py asgi.py settings.py urls.py wsgi.py myapp migration __init__.py admin.py apps.py models.py tests.py urls.py views.py it keeps showing ModuleNotFoundError: No module named 'myapp.urls' views.py from myapp: from django.shortcuts import render, Httpresponse def index(request): HttpResponse('Welcome!') urls.py from myapp: from django.urls import path urlpatterns = [ path('', views.index ), path('create/', views.index) path('read/1/', views.index) ] urls.py from django_project: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('myapp.urls')) ] Thank you! -
Django dynamic localization not working as expected on mobile devices
I have question about show current language on mobile devices if I populate my language list in template dynamically (got from languages array from settings)... So, this code working properly: <a href="#" id="language-en" class="pure-drawer-link{% if LANGUAGE_CODE == 'en' %} active{% endif %}"> EN </a> BUT, when I'm trying this code, I can't achive that active class added to current language: {% for lng in settings.LANGUAGES %} {% if not lng.0 == "ru" %} <a href="#" id="language-{{ lng.0 }}" class="pure-drawer-link{% if LANGUAGE_CODE == '{{ lng.0 }}' %} active{% endif %}"> {{ lng.0|upper }} </a> {% if LANGUAGE_CODE == '{{ lng.0 }}' %} active {% else %} nonactive{% endif %} => this always return nonactive {% endif %} {% endfor %} Can anyone help to understood why this is happening? -
Displaying one field of a django form based on another field
I'm new to django and I've been using it for only 3 months. I have some groups named sprint 1, sprint 2 etc. Every group has a specific user set. What I want to acquire is when a sprint group is selected the user set associated with that sprint group should be shown below so that I could pick an user from the options. forms.py file class BugForm(ModelForm): name = forms.CharField(max_length=200) info = forms.TextInput() status = forms.ChoiceField(choices = status_choice, widget= forms.Select(),initial="Pending", disabled=True) platform = forms.ChoiceField(choices = platform_choice, widget= forms.Select()) phn_number = PhoneNumberField() screeenshot = forms.ImageField() assigned_to = ?? class Meta: model = Bug fields = ['name', 'info','platform' ,'status', 'assign_sprint', 'phn_number', 'screeenshot'] widgets = {'assign_sprint': forms.Select()} views.py file class BugUpload(LoginRequiredMixin, generic.CreateView): login_url = 'Login' model = Bug form_class = BugForm template_name = 'upload.html' success_url = reverse_lazy('index') def form_valid(self, form): form.instance.uploaded_by = self.request.user inst = form.save(commit=True) message = f"Bug created. Bug id:{inst.bug_id}" messages.add_message(self.request, messages.SUCCESS, message) return super().form_valid(form) models.py file class Bug(models.Model): name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") assign_to = models.ForeignKey(User, on_delete=models.CASCADE, related_name='assigned', blank= True, null= True) assign_sprint = models.ForeignKey(Sprint, on_delete= models.CASCADE) phn_number = PhoneNumberField() uploaded_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete= models.CASCADE, related_name='user_name') created_at = models.DateTimeField(auto_now_add= … -
Ajax With Django Not Reload Page But Loop will reload
<div class="container" id="cd"> <div class="row"> <div class="col-2"> <label for="serialno" class="h4 text-center mx-4"> S.No </label> </div> <div class="col-3"> <label for="billno" class="h4 text-center"> Bill No</label> </div> <div class="col-5"> <label for="Items" class="h4 text-center"> Items</label> </div> <div class="col-2"> <label for="total" class="h4 text-center"> Total</label> </div> <hr> </div> {% for b,d in history.items %} <div class="row" id="refresh"> <div class="col-2 py-2"> <label class="h6">{{forloop.counter}}. | {{b.created_at}}</label> </div> <div class="col-3 py-2"> <label class="h5">{{b}}</label> </div> <div class="col-5 py-2"> {% for i in d %} <label class="h6">{{i.itemname}} x {{i.qty}} {{i.subtotal}}</label><br> {% endfor %} </div> <div class="col-2 py-2"> <span class="h6">&#8377;</span> <label class="h6">{{b.grandtotal}}</label> </div> </div> {% endfor %} </div> <script> $(document).on('change','#myform',function(e){ e.preventDefault(); $.ajax({ type:'POST', url:"{% url 'history' %}", data:{ tb1:$('#cal').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, success:function(response){ }, }); }); </script> How Can I reload this {% for b,d in history.items() %} without refresh a page using ajax Any way to change history value using ajax Important Note value processed by onchange event I am trying to reload the loop without a page reload I want to change the history.items() django variable value after the ajax call and corressponding values can be iterated -
How can I render html which extends 'admin/change_list.html'?
I have a requirement where I take CSV file upload and make validations on it before persisting it to the DB. My admin page looks like this: I added this Upload With CSV button. When I click on this, I get to a page which looks like this. Here, I want to redirect back to admin changelist page and notify user that he/she added objects successfully, like this. However, currently my code does not render as I want it to. My code is as follows: def upload_csv(self, request): form = CsvImportForm() data = {"form": form} if csv_file := request.FILES.get("csv_upload"): csv_data = read_csv(csv_file) serializer = CampaignProductCSVUploadSerializer(data=csv_data, many=True) try: with transaction.atomic(): serializer.is_valid(raise_exception=True) old_campaign_id = serializer.return_previous_campaign_id() processed: List[CampaignProduct] = [] for row in csv_data: code = row.get("code") if code is None or not isinstance(code, str) or code.strip() == "": raise serializers.ValidationError(gettext_lazy("Each CampaignProduct object needs to have " "a code.")) obj, *_ = CampaignProduct.objects.update_or_create( code=row["code"], campaign_id=row["campaign"], defaults={ "name": row["name"], "type": row["type"], "is_active": True } ) processed.append(obj.id) CampaignProduct.objects.exclude(id__in=processed).filter(campaign_id=old_campaign_id).update( is_active=False) except Exception as e: raise e return render(request, "admin/csv_upload_success.html", data) return render(request, "admin/csv_upload.html", data) The csv_upload_success.html looks like this: But when I upload the CSV file, I get error as follows: Why can't I just render … -
Connecting a user's MongoDB account to store their data
I'm a beginner, so I'm sorry if this sounds dumb but I want to make a website using django and React where I want to store sensitive information about a user. I want the user to be the only one who can see/access the data entered by them, I do not want to store everyone's data on a MongoDB account made by me. Is it possible to link a MongoDB account specified by the user so that their data is saved into their private MongoDB account? Complete privacy is the goal here. How else can I go about this problem? I tried to look for connecting multiple MongoDB accounts but I didn't find anything related to what I'm looking for. I might have been looking in the wrong direction. Would really appreciate any help! -
Matching query does not exist (Django)
I created a forum website. When pressing on a user profile i get and error in console that library.models.SiteUser.DoesNotExist: SiteUser matching query does not exist. And in the browser it also displays: DoesNotExist at /profile/1/ SiteUser matching query does not exist. Browser highlights this line userprof = SiteUser.objects.get(id=pk) This is my views.py: def userProfile(request, pk): user = User.objects.get(id=pk) **userprof = SiteUser.objects.get(id=pk)** posts = user.post_set.all() post_comments = user.comment_set.all() interests = Interest.objects.all() context = { 'user': user, 'userprof': userprof, 'posts': posts, 'post_comments': post_comments, 'interests': interests } return render(request, 'library/profile.html', context) models.py: class SiteUser(models.Model): page_user = models.OneToOneField(User, on_delete=models.CASCADE) about = HTMLField() profile_pic = models.ImageField('profile_pic', upload_to='covers', null=True) Any help would be greatly appreciated. -
Unable to process Paytm in django rest framework
Im trying to integrate paytm with django rest framework. But don't know why I get checksum mismatch. That is while initiating payment app a checksum is generated but when verifying the checksum it is different. #Views - initiating payment context = { "MID": settings.PAYTM_MERCHANT_ID, "INDUSTRY_TYPE_ID": settings.PAYTM_INDUSTRY_TYPE_ID, "WEBSITE": settings.PAYTM_WEBSITE, "CHANNEL_ID": settings.PAYTM_CHANNEL_ID, "CALLBACK_URL": settings.PAYTM_CALLBACK_URL, "ORDER_ID": str(order.order_number), "TXN_AMOUNT": str(amount), "CUST_ID": str(user.id), } context["CHECKSUMHASH"] = Checksum.generate_checksum( context, settings.PAYTM_MERCHANT_KEY ) return Response({"context": context}) After initiating it Iam sending the CHECKSUMHASH in post request along with MID, ORDERID through postman and check for the checksum validation def VerifyPaytmResponse(response): response_dict = dict() print('in VerifyPaytmResponse 0') if response.method == "POST": data_dict = dict() form = response.POST for key in form.keys(): data_dict[key] = form[key] print('ENTERING HERER') if key == 'CHECKSUMHASH': check_sum = data_dict[key] MID = data_dict['MID'] ORDERID = data_dict['ORDERID'] verify = Checksum.verify_checksum( data_dict, settings.PAYTM_MERCHANT_KEY, check_sum) if verify: STATUS_URL = settings.PAYTM_TRANSACTION_STATUS_URL headers = { 'Content-Type': 'application/json', } data = '{"MID":"%s","ORDERID":"%s"}' % (MID, ORDERID) check_resp = requests.post( STATUS_URL, data=data, headers=headers).json() if check_resp['STATUS'] == 'TXN_SUCCESS': response_dict['verified'] = True response_dict['paytm'] = check_resp return (response_dict) else: response_dict['verified'] = False response_dict['paytm'] = check_resp return (response_dict) else: response_dict['verified'] = False return (response_dict) response_dict['verified'] = False return response_dict This is getting failed because the function to verify … -
how to Subscriber system with django
I want to add an is_subscriber field in django using django ready-made user library Where do I need to add this is_subscriber field? Or how else can I do -
LookupError: No installed app with label 'salesforce'. Did you mean 'salesforce_db'?
After upgrading from Django 2.2 to 3.2 the django-salesforce APP is throwing this error when trying to run my django app Traceback (most recent call last): File "...lib/python3.7/site-packages/django/apps/registry.py", line 156, in get_app_config return self.app_configs[app_label] KeyError: 'salesforce' . . . During handling of the above exception, another exception occurred: Traceback (most recent call last): File "./manage.py", line 14, in <module> execute_from_command_line(sys.argv) File "...lib/python3.7/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "...lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "...lib/python3.7/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File ".../lib/python3.7/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File ".../audit/apps.py", line 18, in ready self.init_auditlog() File ".../audit/apps.py", line 47, in init_auditlog auto_register(all_apps) File ".../audit/utilities.py", line 30, in auto_register app_models = apps.get_app_config(app_name).models File "...lib/python3.7/site-packages/django/apps/registry.py", line 167, in get_app_config raise LookupError(message) LookupError: No installed app with label 'salesforce'. Did you mean 'salesforce_db'? The django-salesforce version is 3.2 salesforce is in INSTALLED_APP, double and triple checked. No syntax errors in model files. -
Best Possible Ways to Translate the language Native to English
I have a website in Django which is in my native language so I want to translate the whole website content in English. I want to know what will be the best possible way to translate the whole website. I will be glad if anyone give me the idea or can share any useful link to make it happen. Thanks much I tried to find out the useful video links and blogs But didn't clear about the best possible ways -
Django Template strange behavior of layout
I have a function which generate a pdf.file and send it by email. And it works perfect. And I have a Table on my frontend like above. In my Django Model - Point 1 set by default as False, by condition if Point 1 is False - Cell 2 is empty, else - marked as Done. When I changing Table via Django form it works fine as well (frontend marked as Done). The problem is when I trying to change this via function which generate a pdf. I have added below lines of code in my pdf.generate Function: def generatePdf(request, pk): point = get_object_or_404(MyObj.objects.select_related('related'), pk=pk) ... email.send(fail_silently=False) point.one = True print(point.one) messages.success(request, 'Success') return HttpResponseRedirect.... at the terminal I got the message that value changed properly from False to True but for some reason Cell 2 in my Table on the frontend still is empty... Part of frontend code: {% for item in object_list %} ... <td> {% if item.one %} <span><i class="fa fa-solid fa-check"></i></span> {% else %} <span></span> {% endif %} </td> ... {% endfor %} Summarizing the above said - why frontend condition working properly if I change via Django form (function) and not if I trying to … -
Django unittests mock.patch will not work if I import the function on top of the file
Hello currently found a problem which I could not find solution to it. I have a django application which communicates with external services in order to write unittests i must patch the functions which call the external services with mock.patch #api_views.py from examplemodule import examplefunction # just example class GetSomeInfoFromExternalService(ApiView): def get(self, *args, **kwargs): if example_function(attrs) == somevalue: return Response({'detail':'OK'}) return Response({'detail':'Not ok'}) here is my other file #tests.py from unittests import mock from django.test import TestCase class MyTestCase(TestCase): @mock.pach('examplemodule.examplefunction') def test_1(self): examplefunction.return_value=123 Like that the patch method will not work, but if I import the examplefunction inside the ApiView.get method is overriding and the mock works. #api_views.py class GetSomeInfoFromExternalService(ApiView): def get(self, *args, **kwargs): from examplemodule import examplefunction # If the import is here the override is working properly if example_function(attrs) == somevalue: return Response({'detail':'OK'}) return Response({'detail':'Not ok'}) -
Django storages is creating folder in s3 bucket when uploading file
I have the following code that i use in django model to upload files to s3 bucket original = S3FileField(storage=S3Boto3Storage(bucket_name='videos-sftp',default_acl=None,region_name='us-east-1',location=''),upload_to='', blank=False, null=False) What is happening is files are being uploaded to following path: https://videos-sftp.s3.amazonaws.com/videos-sftp/ instead of: https://videos-sftp.s3.amazonaws.com/ How do I solve? or is it the package i'm using? -
how to save multiple objects to the database in django rest framework views
so what i'm trying to do is add a new product to my data base using django's restapi but a product may contain multiple categories which are related throught a third many to many model and extra pictures which are ForeignKeyed to the product this is my models.py class Products(models.Model): product_id = models.AutoField(primary_key=True) name = models.CharField(max_length=35, null=False, unique=True) description = models.CharField(max_length=255) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.) main_image = models.FileField(upload_to='shop/images') created_on = models.DateTimeField(blank=True, default=datetime.now) class Category(models.Model): category_id = models.AutoField(primary_key=True) category = models.CharField(max_length=20, null=True, blank=True) created_on = models.DateTimeField(blank=True, default=datetime.now) class Meta: db_table = 'Category' class ProductsCategory(models.Model): productscategory_id = models.AutoField(primary_key=True) category = models.ForeignKey(to=Category, on_delete=models.CASCADE) product = models.ForeignKey(to=Products, on_delete=models.CASCADE) created_on = models.DateTimeField(blank=True, default=datetime.now) class Meta: db_table = 'ProductsCategory' class Pictures(models.Model): picture_id = models.AutoField(primary_key=True) image = models.FileField(upload_to='shop/images') product = models.ForeignKey(to=Products, on_delete=models.CASCADE) created_on = models.DateTimeField(blank=True, default=datetime.now) class Meta: db_table = 'Pictures' and heres what i've tryed: @api_view(['POST']) @permission_classes([IsModerator]) def create_product(request): product_details = ProductsSerializer(request.POST, request.FILES) pictures = PicturesSerializer(request.POST, request.FILES, many=True) category_list = request.POST.getlist("category") if product_details.is_valid() and validate_file_extension(request.FILES.get("main_image")): try: product = product_details.save() if len(category_list) > 0: for i in category_list: if check_category(i): category = Category.objects.get(category=i) ProductsCategory.objects.create(category=category, product=product) else: category = Category.objects.create(category=i) ProductsCategory.objects.create(category=category, product=product) if pictures: for image in request.FILES.getlist("image"): if validate_file_extension(image): Pictures.objects.create(image=image, product=product) else: error = {"error": "invalid … -
Django shell can't see apps(directories with files) that are in the current working directory
I'm fairly new, trying to learn Django. I'm not sure when this issue started, or what caused it, since I used Django shell before and everything worked fine. I've tried different approaches, one of which I saw several times - open Django project from the project folder, not from the outer folder. I did it, and it still doesn't work(pic related) (https://i.stack.imgur.com/swM1J.png) I want to be able to import 'news' app within Django shell since it contains my models, so I can populate my db -
query to loop over records by date in django
I am trying to find a better way to loop over orders for the next seven days including today, what I have already: unfilled_orders_0 = Model.objects.filter(delivery_on__date=timezone.now() + timezone.timedelta(0)) context['todays_orders'] = unfilld_orders_0.aggregate(field_1_sum=Sum('field_1'), field_2_sum=Sum('field_2'),field_3_sum=Sum('field_3'), field_4_sum=Sum('field_4'),field_5_sum=Sum('field_5')) I'm wondering if I can somehow avoid having to do this seven times--one for each day. I assume there is a more efficient way to do this.