Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django not finding static js scripts in the correct folder
I've already run collectstatic and created the static directory in my urls.py, and all other static files work fine (bootstrap, the custom CSS) and other scripts in the same directory work perfectly fine. This is the error code in the console. Failed to load resource: the server responded with a status of 404 (Not Found) ... jquery.formset.js:1 (http://localhost:8000/static/js/django-dynamic-formset/jquery.formset.js) (index):86 Uncaught TypeError: $(...).formset is not a function at (index):86 This is the script section from the rendered html For the second error, I've run into a similar problem before. Moving the jQuery CDN tags above the script itself solved the issue then, but it's not working now. This is my root urls.py urlpatterns = [ path('admin/', admin.site.urls), path('showroom/', include('showroom.urls')), path('', RedirectView.as_view(url='/showroom/', permanent=True)), # Redirect homepage to showroom path('accounts/', include('allauth.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py # Static and media files STATIC_URL = '/static/' STATIC_ROOT = ( os.path.join(BASE_DIR, 'static') ) MEDIA_URL = '/media/' MEDIA_ROOT = ( os.path.join(BASE_DIR, 'media') ) <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="/static/js/django-dynamic-formset/jquery.formset.js"></script> <script type="text/javascript"> $('.formset_row-image_set').formset({ addtext: 'add another', deleteText: 'remove', prefix: 'image_set', }); </script> </body> For context, this is an object creation form. The script allows dynamically created server-side formsets so users can upload individual images. β¦ -
CSRF verification failed on submit after rendering the template via Ajax before
I have a large model formset with initial data, which is injected by ajax through a seperates rendered template. I also pass the csrf token to the template. In the inspector you can also see that the csrf hidden input looks exactly like the other forms on the same page. However, if I want to submit the form, I still get a csrf error. So the complete interface works and also the token is rendered into the template, only I can't submit the form and I don't know why I already tried to render the form without input and inject the inputs via Ajax, but the result was the same. views.py that is called by ajax POST request def render_revolver_table_form(request, product_id, production_step): context = {} context['csrfmiddlewaretoken'] = _get_new_csrf_token template = 'products/product_details/setup_revolver_table.html' SetupRevolverMapFormSet = modelformset_factory(SetupRevolverMap, exclude=( 'product', 'production_step', 'kanal', 'id'), form=SetupRevolverMapForm) setup_revolver_maps = SetupRevolverMap.objects.filter( product=product_id, production_step=production_step).all() context['formset'] = SetupRevolverMapFormSet( queryset=setup_revolver_maps.filter(kanal=1)) return render(request, template, context) injected template <table class="table"> <thead class="thead-dark"> <tr> <!-- Here is content from the formset --> </tr> </thead> <form id="setup_revolver_form_kanal_1" action="" method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value={{csrfmiddlewaretoken}}" /> {{ formset.management_form }} <tbody> <!-- Here is content from the formset --> </tbody> </form> </table> ajax.js csrftoken = $('input[name="csrfmiddlewaretoken"]').val() $.ajax({ url: β¦ -
how to call an url in django view function
I am trying to execute one of the url of urls.py with urllib in djnago view function. After execution i got error like 'url': request.get_host() + new_path, [Thu Oct 17 11:19:27.634475 2019] [wsgi:error] [pid 5120] [remote 202.88.246.2:46648] RuntimeError: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to app.dev-mintaka.aavso.org/member/change_password/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. Is this possible to execute url with urllib inside django view function. @login_required(login_url='http://domain/user/login?destination=apps/member/change_password') def change_password(request): '''Form for user to change their password''' form = SetPasswordForm(user=request.user, data=request.POST or None) if form.is_valid(): form.save() ob = urllib.request.urlopen(url='http://app.dev-mintaka.aavso.org/login/', data=request) messages.success(request, 'Your password has been succesfully updated!') return redirect('hq:profile') return render(request, 'registration/password_change_form.html', {'form': form}) when i execute urllib -
Getting forbidden You don't have permission to access / on this server
i'm trying to deploy django application using apache & mod_wsgi on centos 7. I have added the following lines in the httpd.conf file: Alias /robots.txt /home/centos/sunlife/static/robots.txt Alias /favicon.ico /home/centos/sunlife/static/favicon.ico #Alias /media/ /path/to/mysite.com/media/ Alias /static/ /home/centos/sunlife/static/ <Directory /home/centos/sunlife/static> Require all granted </Directory> #<Directory /path/to/mysite.com/media> #Require all granted #</Directory> WSGIScriptAlias / /home/centos/sunlife/sunlife/wsgi.py <Directory /home/centos/sunlife/sunlife> <Files wsgi.py> Require all granted </Files> </Directory> While trying to access the ip, I am getting Forbidden You don't have permission to access / on this server. -
JavaScript / Django - Displaying Prices on the JQuery date picker calendar
I have implemented a JQuery UI date picker on my "booking" website. I can choose from and to dates, and submit them and make a reservation for the apartment. What I would like to do next is to display prices for each individual day. I also need to be able to do "price-ranges", so one price from date 01-05, another price from 06-12, etc. I'm doing this in Django, as a task I was given, only the calendar is JS, which I don't have much experience with. In the Django backend there is a model where I store the "start_price_date and "end_price_date", aswell as the "price". When I query the backend in JS, this is what I get : 0: "3-10-2019" 1: "999" 2: "4-10-2019" 3: "999" 4: "5-10-2019" 5: "999" 6: "20-10-2019" 7: "666" 8: "21-10-2019" 8: "666" 10: "22-10-2019" 11: "666" So, I get back the dates, and the price for each date. I am having trouble implementing this in the JQuery calendar since I have little to no experience with JS/JQuery. I have tried googling, and went over a few stack overflow posts, tried a few functions but I honestly dont know what I'm doing, this is β¦ -
Django exclude field from all queries
I am running Django on Heroku with zero-downtime feature. This means that during deployment there are two version of code running (old and new) on the same database. That's why we need to avoid any backward incompatible migrations. It there a possibility to exclude a field from Django query on a given model? Let say we have a model (version 1): class Person(models.Model): name = models.CharField() address = models.TextField() In some time in the future we want to move address to the separate table. We know that we should not delete a field for older code to work so Person model may look like (version 2): class Person(models.Model): name = models.CharField() address = models.ForeignKey(Address) _address = models.TextField(db_name='address') This way if old code will query for address it will get it from Person table even if database has been migrated (it will be an old value, but let assume thats not a big issue). How now I can safetly delete _address field? If we will deploy version 3 with _address field deleted then code for version 2 will still try to fetch _address on select, even if it's not used anywhere and will fail with "No such column" exception. Is there β¦ -
Nested For Loop In JINJA for django
My problem is that When I run, Web Page Shows Blank Page, Is there any other way to access Nested For loop for this kind of problem.? This Is my Template. {% for j in N %} {% for k in j %} <h1>{{ k.Name }}</h1> {% endfor %} {% endfor %} and this is view.py post1 = [ { "Name":"Mustafa" } ] post2 = [ { "Name":"Abbas" } ] N = ["post1","post2"] def home_page(request): context = { "post1":post1, "post2":post2, "N":N } return render(request , 'app01/index.html',context) -
How to display sympy output in proper manner
I am very new to coding in Python and using the django. My question: is it possible to get the input-format of an output I get from previous calculations? For example, if I obtain an output is like x**2 how can I get x^2 automatically? https://i.imgur.com/Screenshot_2.png" -
Django unknown column error when trying to get a model objects
I'm trying to set up a web-app that modify an existing MySQL database using Dajngo, the model for my table below was generated via Django inspectdb: class BaseCase(models.Model): base_case_name = models.TextField(blank=True, null=True) version = models.TextField(blank=True, null=True) default = models.TextField(blank=True, null=True) # This field type is a guess. class Meta: managed = False db_table = 'base_case' and here is an SQL of that base_case table in the database : CREATE TABLE `base_case` ( `base_case_name` tinytext, `version` tinytext, `default` bit(1) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; the problem is when I try to get the objects via Django ORM I keep getting this error django.db.utils.OperationalError: (1054, "Unknown column 'base_case.id' in 'field list'") -
SOLUTION to "programming error... relation ... does not exist" on Heroku Django
app is successfully deployed static index page works okay but pages that involve data do not work, giving "programming error ...relation ...does not exit" solution is: heroku run python manage.py migrate --run-syncdb -a appname redeploying didn't work delete all migration files locally, run makemigrations again locally, and push the generated migration files to git: didn't work - what works is this: heroku run python manage.py migrate --run-syncdb -a appname i learned it from here: Relation does not exist on Heroku hope it helps -
tabs link not working in the modal bootstrap with django
I am using django with bootstrap where i have a modal that includes tabs as links where each tab run a function and return the required data. The problem is that one of these tabs is not working... yet if i remove this tab and use it as a button the function works and return the correct values. Note the first 2 tabs run the same function where as the third one run another function. views.py def search(request): # search for person query = request.GET.get('search') print('query===>',query) try: if query != "": print("query is not empty!") try: c = cursor.execute('SELECT Person_.ID,Person_.Full_Name,Person_.Mothers_Name,Person_.Nickname_,Person_.Details,Person_.Address_,Person_.preferedActivity,Person_.Other_Activity,Person_.Other_Descriptive_Details,Person_.Status, Person_.Date_of_Birth,Person_.Place_of_Birth FROM Person_ WHERE Person_.ID LIKE ? or Person_.Full_Name LIKE ? or Person_.Mothers_Name like ? or Person_.Nickname_ LIKE ? or Person_.Details LIKE ? ORDER BY Person_.ID DESC',('%' + query + '%' ,'%' + query + '%', '%' + query + '%', '%' + query + '%', '%' + query + '%')) cc = c.fetchall() paginator = Paginator(cc,20) page_request_var = "page" print("page_request_var===>",page_request_var) page = request.GET.get(page_request_var) print("page====>",page) queryset = paginator.get_page(page) print("queryset=====>",queryset) return render(request,'pictureCard.html', {'c': cc,'countID':countID, 'countFullName': countFullName, 'countMother': countMother, 'countNickname':countNickname, 'countCritical':countCritical, "object_list":queryset, "page_request_var":page_request_var, }) else: print("Search value is empty") return redirect('../../') except pyodbc.DataError: print("DataError: Invalid value!") return redirect('../../') def getEvents(request,id): # search β¦ -
How to serialize distinct queryset in django rest framework?
I have a model that handles Italian's VAT rates. There are three types of rate: 'Ordinaria', 'Ridotta', 'Minima' each type of rate can store multiple values according to a date. For example the current rate for ordinary VAT is 22% and has been set on the 1st oct 2013 but rates have changed during time and I need to store changes and to retrieve the three rates according to a specific date. The model to describe rates is called AliquoteIVA. I use a custom manager to retrieve the current rates as of today or by providing a specific date: class AliquoteIVAManager(models.Manager): def current(self, data): return self.filter(data__lte=data) \ .order_by('descrizione', '-data') \ .distinct('descrizione') class AliquoteIVA(models.Model): """ Modello delle aliquote IVA """ data = models.DateField( blank = False, ) descrizione = models.CharField( blank = False, max_length = 1, default = IVA.IVA_ORDINARIA, choices = IVA.IVA_TIPOLOGIA_CHOICES, ) aliquota = models.DecimalField( blank = False, null = False, default = '0', max_digits=19, decimal_places = 2, validators = [MinValueValidator(0.0)], ) objects = AliquoteIVAManager() def __str__(self): str_aliquota = "{0:.2f}".format(self.aliquota).replace('.', ',') return "IVA {descrizione} al {aliquota}% in vigore dal {data}".format( descrizione=self.get_descrizione_display(), aliquota=str_aliquota, data=self.data ) class Meta: ordering = ('-data', 'aliquota',) verbose_name = 'Aliquota IVA' verbose_name_plural = 'Aliquote IVA' I've tested β¦ -
How can we setup Malayalam Language in Python Django?
I would like to create a Python Django website in "Malayalam". I think we can implement that using the Localisation method while enabling USE_I18N = True, USE_L10N = True in "settings.py". Is there any apps available for performing these? -
AttributeError: 'str' object has no attribute '_meta' / Python 3.6
File "manage.py", line 15, in execute_from_command_line(sys.argv) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 327, in execute self.check() File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\commands\migrate.py", line 62, in _run_checks issues.extend(super(Command, self)._run_checks(**kwargs)) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 25, in check_admin_app errors.extend(site.check(app_configs)) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py", line 81, in check errors.extend(modeladmin.check()) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\options.py", line 117, in check return self.checks_class().check(self, **kwargs) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 526, in check errors.extend(self._check_list_filter(admin_obj)) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 697, in _check_list_filter for index, item in enumerate(obj.list_filter) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 697, in for index, item in enumerate(obj.list_filter) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\checks.py", line 740, in _check_list_filter_item get_fields_from_path(model, field) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\utils.py", line 500, in get_fields_from_path parent = get_model_from_relation(fields[-1]) File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\utils.py", line 451, in get_model_from_relation return field.get_path_info()[-1].to_opts.model File "C:\Users\INUSCG\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\fields\related.py", line 723, in get_path_info opts = self.remote_field.model._meta AttributeError: 'str' object has no attribute '_meta' I am facing this Error on python 3.6, I got this error when i migrate my django project -
Django: Cannot Update the Value of IntegerField
I have an IntegerField in my model and I try to update it in the admin page. No matter what value I input (e.g. 100, 200), the value is restored to 0 after saving it. models.py class inputform(models.Model): ... age = models.IntegerField('Age', blank=True, null=True) ... I have tried change the value via SQL in the database directly and it updated successfully. However, when I read it in the admin page and saved it without any change, the value restore to 0. Is there any wrong with my code? Thanks! -
Making field required = False on ModelForm
I've got a model of UserCoupon that a user can create and edit. Upon edit, I only want them to be able to edit the 'code' field on the instance of UserCoupon if there are no orders associated with that code. When there are orders associated with that coupon code, rather than outputting {{form.code}} on the edit coupon form, I'm outputting {{form.instance.code}}. When the user attempts to submit the form, I get an error saying that the field is required. How can I make this field not required or otherwise address this situation so that the user can submit the form when one of the fields defined for the model form shows up in the template as an instance of the field rather than an input box? Models.py class UserCoupon(models.Model): code = models.CharField(max_length=15, unique=True) amount = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) forms.py class EditUserCouponForm (forms.ModelForm): class Meta: model = UserCoupon def __init__(self, *args, **kwargs): self.user = kwargs.pop('user',None) super(EditUserCouponForm, self).__init__(*args, **kwargs) def clean(self): cleaned_data = super(EditUserCouponForm, self).clean() template {% if coupon_order_count > 0 %} {{form.instance.code}} {% else %} {{form.code}} {% endif %} Thanks! -
Django Unittest mockset patching doens't always work
I wrote the following unit test, which succeeds when I run it individually via the VSCode IDE / unit test browser. api\test\test_views.py: class ProductListViewTest(APITestCase): def test_get_products(self): mock_products = MockSet() mock_products.add(MockModel( mock_name='e1', prod_id='1') # hit the API endpoint client = APIClient() with patch('api.models.Product.objects', mock_products): response = client.get(reverse('product-list')) # expected result expected = [ { 'prod_id': '1', } ] serialized = ProductSerializer(expected, many=True) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, serialized.data) api\views.py: from api.models import Product class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer api\urls.py: # ... path('product/', views.ProductListView.as_view(), name='product'), # ... However, as soon as I run it by python manage.py test, it fails, because response.data is an empty array - which probably means it is quering the empty test_ database and not the patched object. I tried to patch with patch('api.views.Exception.objects', mock_products): instead of with patch('api.models.Exception.objects', mock_products): but then the unittest fails in both cases. -
inilah 13 cara menggugurkan kandungan yang paling banyak di minati 082226222691
Info Konsultasi Wa : 082226222691, Inilah 12 Obat aborsi di jakarta Yang Paling Banyak Di Minati, Jual 13 Jenis Dan Merk Obat Aborsi Di Kota Bandung Provinsi Jawa Barat, klinik terpecaya untuk : menggugurkan kandungan , Tersedia juga : jamu penggugur kandungan, cara menggugurkan kandungan dengan paracetamol, cara menggugurkan kandungan 1 bulan, obat terlambat haid , cara menggugurkan kehamilan , penggugur kandungan, semua akan teratasi jika anda memesan obat, janin 1 bulan, cara menggugurkan , cara mengatasi telat haid, cara menggugurkan kandungan 100 berhasil, Kami Menberikan Pelayanan Semaksimal Mungkin Dengan Pengalaman Kami, cara gugurin kandungan, cara menggugurkan janin, cara menggugurkan hamil muda, cara menggugurkan kandungan 2 bulan, telat datang bulan 1 bulan, cara gugurkan kandungan, cara menggugurkan kandungan 2 minggu, makanan penggugur kandungan, penyebab telat datang bulan selama 2 bulan, cara aborsi, sitotek, cara menggugurkan kandungan 4 bulan, Mengggurkan kandungan alias aborsi sering diidentikkan dengan mengakhiri kehamilan yang tidak diinginkan cara menggugurkan kandungan usia 1 bulan, Jangan Untuk Juga Menonton video aborsi, cara menggugurkan kandungan dengan cepat, cara menggugurkan bayi, cara menggugurkan kandungan 1 minggu, kandungan 3 bulan, cara menggagalkan kehamilan, cara menggugurkan kandungan secara tradisional, Jangan Membeli Produk Di Warung-Warung Untuk Obat Telat Bulan Anda, kenapa bodrex dan sprite β¦ -
TypeError: Direct assignment to the reverse side of a related set is prohibited. Use order_items.set() instead
I have Ordel model in my project models.py class Order(models.Model): order_id = models.CharField(max_length=50, unique=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True, related_name='orders') total = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items') product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='order_items') quantity = models.PositiveIntegerField(null=True, blank=True, default=1) serializers.py class OrderSerializer(serializers.ModelSerializer): order_items = serializers.StringRelatedField(many=True, required=False) class Meta: model = Order fields = ['id', 'user', 'total', 'order_items'] def create(self, validated_data): return Order.objects.create(**validated_data) class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ['id', 'order', 'product', 'quantity'] finally views.py class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer def perform_create(self, serializer): try: purchaser_id = self.request.data['user'] user = User.objects.get(pk=purchaser_id) except: raise serializers.ValidationError( 'User was not found' ) cart = user.cart for cart_item in cart.items.all(): if cart_item.product.inventory - cart_item.quantity < 0: raise serializers.ValidationError( 'We do not have enough inventory of ' + str(cart_item.product.name) + \ 'to complete your purchase. Sorry, we will restock soon' ) total_aggregated_dict = cart.items.aggregate(total=Sum(F('quantity')*F('product__price'),output_field=FloatField())) order_total = round(total_aggregated_dict['total'], 2) order = serializer.save(customer=user, total=order_total) order_items = [] for cart_item in cart.items.all(): order_items.append(OrderItem(order=order, product=cart_item.product, quantity=cart_item.quantity)) cart_item.product.available_inventory -= cart_item.quantity cart_item.product.save() OrderItem.objects.bulk_create(order_items) cart.items.clear() def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) when send Post request to the url /orders/ it throws error β¦ -
Visual studio code breakpoint set to grey color & not working.error(may be excluded because of "justMyCode" option)
I have set breakpoint in Django core library in visual studio code but when I am starting debugging of my project , those debug point color changed from red to grey & show me notification like below. Breakpoint in file excluded by filters. Note: may be excluded because of "justMyCode" option (default == true). I have set justmycode value to false from visual code option but still I am not able to set breakpoint. Even I have read SO question related but not able to solve my issue so I have to post my question. I have tried to set localroot & remoteroot but not working even. -
How to update history record in Django?
I got question about Django history. When I am in admin and change something in database, it will make an record in history of that object, that I made it or I update some record of that specific object. When I paste the data to database through some form (when the user is log in), it will not make an record in history. I also tried to update value and it works fine but it will not make and record in history, that this and this was changed... Can someone help me how to do it please? What should I add to this part of code? t = Pool.objects.get(pk=Pools_id) t.Status = "New" t.save() return HttpResponseRedirect('#') -
Django - change datafield on database
i am creating a real estate website in Django. I want users to insert/delete images for their properties. ItΒ΄s all working as expected, except the delete images. In my views.py i have the code: listing = Listing.objects.get(id=1511) if listing: listing.photo_5 = None listing.save(['photo_5']) return True photo_5 is an Imagefield and i want to change the value of that field in database to None. I am saving the image to media folder and save the url in database. photo_5 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True) Then when the user clicks in trash can icon, i have an ajax request (working and receives response from view) to delete the image from database. But there is the problem, i am not able to update the url in database or to delete. I already tried with update Listing.objects.all().filter(id = 1511).update(photo_5 = None) It seems that i can not change the value of photo_5. Why is not changing? -
is it bad to have en directory in locale? is there any use for it?
the main language is English for my website, some tutorials suggest to use django-admin makemessages -a and others suggest to use django-admin makemessages -l -de but when i use -a it make the en-us directory as shown below and it seems pretty much useless or is it? it there any merit for having a en-us directory for a website with English as it's main Lang? or should i just delete it? . βββ db.sqlite3 βββ some_industry βββ locale β βββ en_us β β βββ LC_MESSAGES β β βββ django.po β βββ de β βββ LC_MESSAGES β βββ django.po βββ machine_request β βββ __init__.py β βββ admin.py β βββ locale β β βββ en_us β β β βββ LC_MESSAGES β β β βββ django.po β β βββ de β β βββ LC_MESSAGES β β βββ django.po β βββ migrations β βββ static β β βββ machine_request β βββ templates β βββ urls.py βββ manage.py βββ users βββ __init__.py βββ admin.py βββ locale β βββ en_us β βββ de βββ views.py -
why is form.is_valid returns false?with this error?
what is this error???? <ul class="errorlist"><li>username<ul class="errorlist"><li>This field is required.</li></ul></li><li>password<ul class="errorlist"><li>This field is required.</li></ul></li></ul> -
Removing Brackets from itertools combination list results
I have this code import itertools import random def gen_reset_key(): key = random.randint(100, 199) return key key_combinations = list(itertools.combinations(str(gen_reset_key()), 2)) key_one = key_combinations[0] key_two = key_combinations[1] key_three = key_combinations[2] print("Key one is: {}".format(key_one)) print("Key two is: {}".format(key_two)) print("Key three is: {}".format(key_three)) The output is: Key one is: ('1', '9') Key two is: ('1', '9') Key three is: ('9', '9') I want to remove the brackets and speech marks from the output. How can I achieve that? so that my output would be: Key one is 19 Key two is 19 Key three is 99