Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter data from two tables having many to many relation django
I am new python django. I just came to scenario where i want to filter out data of slots from slot table of specific customer.Tables are connected using third table appointment.In appointment table i am storing customer id and slot id associated with that customer.How to filter out customer all slots associated with it? This is structure of tables and their relation with each other. Please help me out to solve it. I know by using join in sql i get data. But i want to filtering data in python django so how i can apply joins in django to filter data. I googled a lot but didn't get any proper answer. Please Provide proper explanation with your answer. -
Django model choice example
I have the following models: POSSIBLE_POSITIONS = ( (1, 'Brazo'), (2, 'Muñeca'), (3, 'Pierna'), (4, 'Pie'), ) class Device(models.Model): id = models.CharField(max_length=10, primary_key=True) class User(models.Model): id = models.CharField(max_length=10, primary_key=True) device = models.ForeignKey(Device, blank=True, null=True, on_delete=models.SET_NULL) position = models.CharField(max_length=1, choices=POSSIBLE_POSITIONS, default=1) I would like to know how to work with that dictionary. If I go to Django shell and I do the following it works: user = User(pk=1, position=12312) Why this work? 12312 is not a possible choice from POSSIBLE_POSITIONS. How I can exchange the number for the String? Also, how I can show all this options on a selector when creating a new user via html? -
How Django verifies CSRF?
According to my understanding, the way Django verifies CSRF is by comparing the request.POST.get('csrfmiddlewaretoken', '') | request.META.get(settings.CSRF_HEADER_NAME, '') == request.session.get(CSRF_SESSION_KEY) | request.COOKIES[settings.CSRF_COOKIE_NAME] CsrfViewMiddleware Now the way, these 2 tokens (one from LHS and one from RHS) are compared is by the deciphering using following function _unsalt_cipher_token The 2 tokens being compared, are different, but are deciphered to the same "secret". My question is shouldn't Django ensure that they are different ? Whats the purpose of using the 2 different tokens(and the overhead of deciphering them),if not ensuring they are different ? -
Can I make a folder of form and views and use an __init__.py file like models and test?
I would like to keep my views and forms separate, just like you can with models. Are you able to make a directory of views and forms, and if so, what goes in the init.py files for each -
Query Complex using Django 2.0
I'm wirting a query using Django, I have my model: class Recommender(models.Model): customer = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="recoCustomer") brand = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="recoBrand") recommender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="recommender") authorized = models.ForeignKey(State, default=5, help_text=_('Recommend state (5-pending, 6-approved, 2-canceled).'), ) dateTime = models.DateTimeField(auto_now=True) The first requeriment was: I need all records where the customer is equal to loggued in user and authorized is equal to 5. My first query was: Recommender.objects.all().filter( customer=request.user, authorized=State.objects.get(pk=5) ) However, right now I need all records where the customer is equal to loggued in user and authorized is equal to 5 , but if exist a couple (brand_id, customer_id) where authorized flag is equal to 6 , the query must ignore the anothers records of the couple (brand_id, customer_id) with authorized_flag is equal to 5. ------------------------------------------------------------------ Records on table Recommenders ------------------------------------------------------------------ | authorized | brand_id | customer_id | recommender_id | dateTime | |------------|----------|-------------|----------------|----------| | 5 | 1 |32 |31 | ... | | 5 | 1 |32 |19 | ... | | 5 | 9 |32 |8 | ... | | 5 | 28 |32 |8 | ... | | 6 | 1 |32 |8 | ... | In the previous table, the query should not return records with couple (brand_id, … -
form of redirect to the new page by slug in django 2.0
how to create a form of redirection to the url \ my urls.py urlpatterns = [ url(r'^$', IndexView.as_view(), name='index'), url(r'^logout', login_required(LogoutView.as_view(), login_url='/'), name='logout'), url(r'^update/(?P<slug>[\w-]+)$', UserUpdate.as_view(), name='user_update'), ] Need a form where i can input a slug of user and below press a button "change" that will redirect me to "exmaple.com/update/(inputedslughere)" -
Encrypting packets send by django
I have django as rest API and android app as client. While sending or receiving requests from server, using a packet sniffer on the client i can clearly see the json-object's and the server IP address where it came from. Is there any way to make it not so easy for a simple packet sniffer to see the packets sent by server? -
Why does django error "column posts_post.category_id does not exist" keep coming back up?
I have a django blog project which has the following core models: Models.py class Category(models.Model): parentCategoryName = models.ForeignKey('self', blank=True, null=True) parentCatSlug = models.SlugField(null=True, blank=True) categoryName = models.CharField(max_length=200, null=True) categorySlug = models.SlugField(null=True, blank=True) def __str__(self): full_path = [self.categoryName] k = self.parentCategoryName while k is not None: full_path.append(k.categoryName) k = k.parentCategoryName return ' -> '.join(full_path[::-1]) class Meta: verbose_name_plural = "categories" def save(self, *args, **kwargs): self.categorySlug = slugify(self.categoryName) self.parentCatSlug = slugify(self.parentCategoryName) super(Category, self).save(*args, **kwargs) class Post(models.Model): title = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) summary = models.CharField(max_length=500, default=True) body = RichTextUploadingField() pub_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, default=True) titleSlug = models.SlugField(blank=True) authorSlug = models.SlugField(blank=True) editedimage = ProcessedImageField(upload_to="primary_images", null=True, processors = [Transpose()], format="JPEG") show_in_posts = models.BooleanField(default=True) def save(self, *args, **kwargs): self.titleSlug = slugify(self.title) self.authorSlug = slugify(self.author) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title When I run makemigrations and migrate, all works fine initially, but then after a while, I get the error above. I've posted a question on this previously, and the solution was to drop the database and re-create it. This still works, but it happens frequently, so I keep having to drop and re-create. Can anyone help explain why this is seemingly sporadically happening? -
django m2m_changed not working
i have simple code, bug not working! after added a tag to content not called tag_update_count_use! models .py class Tag(models.Model): count_use = models.PositiveIntegerField(_('count use'), default=0) def update_count_use(self, delta): self.count_use += delta self.save(update_fields=['count_use']) class Content(models.Model): tags = models.ManyToManyField('Tag', blank=True, verbose_name=_('tags')) signals.py from django.db.models.signals import m2m_changed from django.dispatch import receiver @receiver(m2m_changed, sender=Content.tags) def tag_update_count_use(sender, **kwargs): print(kwargs) return kwargs __init__.py default_app_config = 'content.apps.ContentConfig' apps.py class ContentConfig(AppConfig): name = 'content' verbose_name = _('content') def ready(self): import content.signals according to https://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed i changed code to : @receiver(m2m_changed, sender=Content.tags.though) but i receive this error: AttributeError: 'ManyToManyDescriptor' object has no attribute 'though' -
Define button action with django
I want to build a calendar with django. Now i want to switch between months with buttons but every tutorial shows how one can define actions with Java Script. I was wondering if and how i can define a action for my button with django only and if there is any disadvantage in doing so? Thanks in advance! =) -
difference between using js render template and using include tag in Django
** I have separated my form from my HTML file by using include tag** {% block content %} <div class="col-10 col-md-6 mx-auto"> {% include 'snippets/payment_form.html' with public_key=public_key next_url=next_url%} </div> {% endblock %} Then, I knew there is jsrender provided in the following link: https://github.com/BorisMoore/jsrender could anyone please specify the differences between the two approaches. -
Django admin getting 400 while trying to upload multiple images from admin panel
I am trying to upload images from .zip archive and data that relates for them from .xlsx. Here is admin.py file where I am trying to import images @admin.register(ImageModel) class ImageAdmin(admin.ModelAdmin): change_list_template = "entities/images_changelist.html" list_display = ('name', 'img') @staticmethod def img(obj): return mark_safe( f'<img src="{obj.image.url}" height="100">') if obj.image else None def get_urls(self): urls = super().get_urls() my_urls = [ path('import-images/', self.import_images), ] return my_urls + urls def import_images(self, request): form = forms.ImagesUploadForm() if request.method == "POST": ...Parsing them... self.message_user(request, "Your images have been imported") return redirect('/admin/images/imagemodel/') return render(request, "admin/images_form.html", {"form": form}) Here is html of form: {% extends 'admin/base.html' %} {% block content %} <div> <form action="." method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Import images</button> </form> </div> {% endblock %} Here is my form: class ImagesUploadForm(forms.Form): excel_file = forms.FileField() zip_file = forms.FileField() It works good on my local machine but I am getting 400 error on my dev server. Also when I'm adding if form.is_valid(): I always get False and form.errors == '' -
Django login auth form
I trying to grasp this new field of webbprogramming and is it possible to make the user login from a form which is built into the html file itself? If so, how can i achieve this? <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><i class="fa fa-sign-in"></i> Login </a> <form class="dropdown-menu p-4 dropdown-menu-right" method="post" action="#"> {% csrf_token %} <div class="form-group"> <label for="id_username">Username</label> <input id="id_username" name="username" type="text" class="form-control" placeholder="user.name"> </div> <div class="form-group"> <label for="id_password">Password</label> <input id="id_password" type="password" class="form-control" placeholder="Password"> </div> {% if form.errors %} <p class=" label label-danger"> Your username and password didn't match. Please try again. </p> {% endif %} <input type="submit" value="Login" class="btn btn-primary" /> <input type="hidden" name="next" value="{{ next }}" /> </form> </li> -
Select2 control trying to load all the data when loading data remotely using a custom data loader?
I've been struggling with this issue for some time. I'm using select2 version 4 and implementing the following custom data loader with infinite scrolling. I'm able to get this to work perfectly using the following fiddle. http://jsfiddle.net/jgf5fkfL/117/ My issue occurs when I use the following script with my django application. The data doesn't seem to use the custom loader and it tries to pull in the entire table, instead of querying the minimumInputLength of 3. $.fn.select2.amd.require( ['select2/data/array', 'select2/utils'], function (ArrayData, Utils) { function CustomData($element, options) { CustomData.__super__.constructor.call(this, $element, options); } function contains(str1, str2) { return new RegExp(str2, "i").test(str1); } Utils.Extend(CustomData, ArrayData); CustomData.prototype.query = function (params, callback) { if (!("page" in params)) { params.page = 1; } var pageSize = 50; var results = this.$element.children().map(function (i, elem) { if (contains(elem.innerText, params.term)) { return { id: [elem.innerText, i].join(""), text: elem.innerText }; } }); callback({ results: results.slice((params.page - 1) * pageSize, params.page * pageSize), pagination: { more: results.length >= params.page * pageSize } }); }; $(".selectuserlist").select2({ ajax: {}, allowClear: true, width: "element", multiple: true, dataAdapter: CustomData }); }); I'm loading the data into my django html with the following: <div class="col"><h4 style="margin-top: 0"><strong>User Search</strong></h4><select class ="selectuserlist" multiple="multiple" value = "{{ userid }}" style="width: … -
Dango Rest Framework 3.7.7 does not handle Null/None ForeignKey values
I am getting an error with Django Rest Framework when my ForeignKey contains a null value. unit = models.ForeignKey( SubLocation, on_delete=models.CASCADE, related_name='unit', blank=True, null=True, ) class AssetSerializer(serializers.ModelSerializer): unit = serializers.PrimaryKeyRelatedField( source='unit.name', allow_null=True, default=None, queryset=SubLocation.objects.all(), ) class Meta: model = Asset fields = ('pk', 'unit', ) Accessing the data attribute of this serializer, when the unit foreign key field is None >> ass = Asset.objects.first() >> AssetSerializer(ass).data Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python36\lib\site-packages\rest_framework\serializers.py", line 537, in data ret = super(Serializer, self).data File "C:\Python36\lib\site-packages\rest_framework\serializers.py", line 262, in data self._data = self.to_representation(self.instance) File "C:\Python36\lib\site-packages\rest_framework\serializers.py", line 491, in to_representation attribute = field.get_attribute(instance) File "C:\Python36\lib\site-packages\rest_framework\relations.py", line 177, in get_attribute return get_attribute(instance, self.source_attrs) File "C:\Python36\lib\site-packages\rest_framework\fields.py", line 100, in get_attribute instance = getattr(instance, attr) AttributeError: 'NoneType' object has no attribute 'unit' As you can see, setting allow_null still does not work, and drf seems to be complaining about the NoneType object. How am I able to fix this error so that I can use null values with drf? -
Running the "manage.py" file with runserver to start my Django Project isnt working
I started learning Django and immediatly the first error occurred, when I tried to run the project for the first time. I typed into the command line: C:\Users\me\Desktop\website> python manage.py runserver This is the error code i received after: Performing system checks... System check identified no issues (0 silenced). April 05, 2018 - 15:05:49 Django version 2.0.4, using settings 'website.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x05E04E88> Traceback (most recent call last): File "E:\Programme\python\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "E:\Programme\python\lib\site-packages\django\core\management\commands\runserver.py", line 142, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "E:\Programme\python\lib\site-packages\django\core\servers\basehttp.py", line 163, in run httpd = httpd_cls(server_address, WSGIRequestHandler, ipv6=ipv6) File "E:\Programme\python\lib\site-packages\django\core\servers\basehttp.py", line 66, in __init__ super().__init__(*args, **kwargs) File "E:\Programme\python\lib\socketserver.py", line 453, in __init__ self.server_bind() File "E:\Programme\python\lib\wsgiref\simple_server.py", line 50, in server_bind HTTPServer.server_bind(self) File "E:\Programme\python\lib\http\server.py", line 138, in server_bind self.server_name = socket.getfqdn(host) File "E:\Programme\python\lib\socket.py", line 673, in getfqdn hostname, aliases, ipaddrs = gethostbyaddr(name) UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfc in position 1: invalid start byte I also tried to exchange "python" with the path: E:\Programme\python\python manage.py runserver But it doesn't seem to make any difference. I also checked the code first multiple times to see if I … -
Django setting.Databases is improperly configured
I am using django 1.10 with mongodb I migrated from django-nonrel 1.5... I made the changes required for my project run on django 1.10... pythom manage.py runserver doesn't give any errors... But while creating superuser or while migrating it gives the improperly configured error. -
Incorrect work memcached + docker-compose: returns None
I'm need you're help.. I trying to use memcached + docker-compose but to me all returns None.. I make port forwarding web with memcached. Base cache is given 11211 port. View.py is is written for an example. What am I doing wrong? viesw from django.core.cache import cache def show_category(requests): categorys_name = CategoryNews.objects.all() cache_key = 'category_names' cache_time = 1800 result = cache.get(cache_key) print(result) if result is None: result = categorys_name cache.set(cache_key, result, cache_time) return render(requests, 'home_app/category.html', {'categorys_name':categorys_name}) return print('No none') settings CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '0.0.0.0:11211', } } Docker-compose sersion: '3' services: db: restart: always image: postgres web: restart: always working_dir: /var/app build: ./testsite entrypoint: ./docker-entrypoint.sh volumes: - ./testsite:/var/app expose: - "80" - "11211" depends_on: - db ngnix: restart: always build: ./ngnix ports: - "80:80" volumes: - ./testsite/static:/staticimage - ./testsite/media:/mediafilesh depends_on: - web memcached: image: memcached:latest entrypoint: - memcached - -m 64 ports: - "11211:11211" depends_on: - web -
Django way to query multi column fulltext index in MySQL?
I'm trying to query a multi-column fulltext index in Django using a Lookup. I have the following lookup @CharField.register_lookup @TextField.register_lookup class Search(models.Lookup): lookup_name = "search" def as_mysql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return "MATCH (%s) AGAINST (%s IN BOOLEAN MODE)" % (lhs, rhs), params This is inspired from the lookup that I found here in the Django docs. However, this appears to only work for Fulltext indexes of a single column. I'm trying to do a query over two columns. Below is my MySQL table for reference: CREATE TABLE Entry ( entryID INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, username VARCHAR(20) NOT NULL, time DATETIME NOT NULL, modified BOOLEAN NOT NULL, message TEXT NOT NULL, FULLTEXT (message, username), PRIMARY KEY (entryID) ); Of course when I try to do a query using the lookup above, I get an error: "django.db.utils.OperationalError: (1191, "Can't find FULLTEXT index matching the column list" I noticed there is Django code to accomplish this using a SearchVector, but only for PostgresSQL. Additionally, I realize there is a package that someone wrote to do this at https://blog.confirm.ch/django-1-8-mysql-mariadb-full-text-search/ However, I really wanted to know if there is a … -
Tensorflow: feed_dict key as Tensor error with threading
I am running a django server and just realised I am facing a problem when I start a daemon thread and load my weights. Has anyone faced the same problem and how you managed to solve it? I used to solve this problem with clear_session method from Keras but now it seems that it doesn't work. Exception in thread Thread-7: Traceback (most recent call last): File "/Users/ale/.virtualenvs/LoceyeCloud/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1064, in _run allow_operation=False) File "/Users/ale/.virtualenvs/LoceyeCloud/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3035, in as_graph_element return self._as_graph_element_locked(obj, allow_tensor, allow_operation) File "/Users/ale/.virtualenvs/LoceyeCloud/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3114, in _as_graph_element_locked raise ValueError("Tensor %s is not an element of this graph." % obj) ValueError: Tensor Tensor("Placeholder:0", shape=(3, 3, 1, 64), dtype=float32) is not an element of this graph. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/Users/ale/platform/Server/server_back/server_backend.py", line 196, in execute eyetracker = LoceyeEyetracker(self.screen_dimensions) File "/Users/ale/platform/Server/server_back/LoceyeEyetracker.py", line 24, in __init__ self.iris_detector = IrisDetectorCnn(weights_filename, blink_filename) File "/Users/ale/platform/Server/server_back/IrisDetectorCnn.py", line 17, in __init__ self.model = load_model(model_filename) File "/Users/ale/.virtualenvs/LoceyeCloud/lib/python3.6/site-packages/keras/models.py", line 246, in load_model topology.load_weights_from_hdf5_group(f['model_weights'], model.layers) File "/Users/ale/.virtualenvs/LoceyeCloud/lib/python3.6/site-packages/keras/engine/topology.py", line 3166, in load_weights_from_hdf5_group K.batch_set_value(weight_value_tuples) File "/Users/ale/.virtualenvs/LoceyeCloud/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 2370, in batch_set_value get_session().run(assign_ops, feed_dict=feed_dict) File "/Users/ale/.virtualenvs/LoceyeCloud/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 889, in … -
Django multilanguage text and saving it on mysql
I have a problem with multilanguage and multi character encoded text. Project use OpenGraph and it will save in mysql database some information from websites. But database have problem with character encoding. I tryed encoding them to byte. That is problem, becouse in admin panel text show us bute and it is not readable. Please help me. How can i save multilanguage text in database and if i need encode to byte them how can i correctly decode them in admin panel and in views -
How to handle making one and only one "primary" product ID per product
Life used to be simple. We had a table of products each of which has a product code. Unfortunately, we are a small manufacturer with relationships with several large distributors, who very much want us to use their product codes when they order from us (and sometimes, not even with a courtesy description for a human-type look-up!). so it's now looking like Class ProductCode( models.Model) item_desc = models.ForeignKey( ItemDesc, related_name=product_codes) code = models.CharField( ...) customer = ... # FK or Character, unique with code primary = models.BooleanField( ... ) # wrong way? ... Class ItemDesc( models.Model) # code = models.CharField( ...) # what we used to do primary_code = models.OneToOneField( ProductCode, ... ) # maybe? ... How can I make sure that there is always one and only one primary product code per ItemDesc? (Primary being the one that we use internally to refer to items, for example in stock, and for direct sales to end-users). Conceptually I make primary unique with item_desc but that doesn't solve two related problems It would have to become an integer, with (say) 1 = primary and 2..N existing only to make non-unique and be treated like false. How to make it so an … -
Submiting files and data using django form and ajax
This question has been asked before , but yet i have not found any that seems to work with my project. My question is how can i submit django form using ajax . The django-form data has imagefile and files included in the form . Most of the examples i tried could not submit imagefile and files submited. bellow is my javascript <script> $(document).ready(function(){ e.preventDefault(); var formobj=$(this); var formurl=formobj.attr("data-url"); var formdata = new FormData(this); $.ajax({ url:formurl, type:'POST', data:'formdata', mimeType:'multipart/form-data', success:SuccessFunction, error:ErrorFunction, }); function SuccessFunction(data){ print(data); } function ErrorFunction(data){ print("error"); } }); }); </script> Form.py class PostProductForm(forms.ModelForm): class Meta: model = MfrProductPosting widgets={ 'producttype':forms.Select(attrs={'id':'post-text',}), 'productname':forms.TextInput(attrs={'id':'post-text1','placeholder':'Name of product'}), 'productImage':forms.ClearableFileInput(attrs={'id':'post-image1',}), 'productImage1':forms.ClearableFileInput(attrs={'id':'post-image2',}), 'productImage2':forms.ClearableFileInput(attrs={'id':'post-image3',}), 'productImage3':forms.ClearableFileInput(attrs={'id':'post-image4',}), 'productcaption':forms.Textarea(attrs={'id':'caption','placeholder':'Write something about product.To help distributors understand what your product is all about.................'}), 'productquatity':forms.TextInput(attrs={'id':'quantity','placeholder':'Product quantity'}), 'budget':forms.TextInput(attrs={'id':'budget','placeholder':'ProductCost Currency'}), } exclude=('slug','created','company','creator','promote',) fields=('producttype','productname','productImage1','productImage2','productImage3','productImage','productcaption','productquatity','budget') my view.py def YourViewOfYourCompanyProfile(request,slug): instance = get_object_or_404(ManufacturerProfile,Q(user=request.user),slug=slug) postproduct=MfrProductPosting.objects.all() form =PostProductForm(request.POST ,request.FILES) if request.is_ajax(): if form.is_valid(): instance1=form.save(commit=False) instance1.creator=request.user instance1.company=instance instance1.save() data = { 'message':'Product posted' } return JsonResponse(data) context={'instance':instance, 'postproduct':postproduct, 'form':form} template_name="manufacturerprofile/mycompanyprofilepage.html" return render(request,template_name,context) when i try submitting the form i get this error in the console TypeError: can't convert undefined to object. Please i need help in submitting this form with all data using ajax -
Django: annotate queryset using extra() and select where date
I'm trying to annotate each product with a total of the weight sold in the last 7 days. The extra() modifier is used instead of annotate() because there's another query that causes incorrect results when both are annotated. class Order(models.Model): date = models.DateField() class OrderLine(models.Model): order = models.ForeignKey(Order) weight = models.DecimalField() class Product(models.Model): name = models.CharField() The query below results in ProgrammingError: missing FROM-clause entry for table "order". I'm not fully familiar with SQL so I'm not entirely sure how to fix this. Do I need to do some sort of a join on order to get the accurate date for each OrderLine? query = Product.objects.all() date = timezone.now() - timedelta(days=7) query = query.extra( select={ 'weight_sold': "select sum(order_orderline.weight) from order_orderline where order_orderline.product_id = product_product.id and order_orderline.order.date > %s" }, select_params=(date,) ) -
Language for backend for full stack web developer keeping the job in mind
Should I go for Django or Nodejs for backend if I know both python and Javascript? I know the differences but I am confused because in India most of the internships are for nodejs and very few are for django! Please Suggest..