Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python3 : serializing WHERE clause (in Django)
I am using Django 3.0 and a WMS server. Django serves as a proxy for the WMS server, i.e. all requests to the WMS server are sent to Django, which controls the user rights and then sent to the internal WMS server. The same is done for the WMS server's responses. My users are to be able to query the WMS server using filters, i.e. they may set filters that are taken in account by the WMS server for filtering the features that are in the server response. These filters are to be kept in the Django user session. I also need to store these filters in the database so that users find them again at the next session. I am creating a Python class for this. Each set of filters chosen by the user would be an instance of the class. Then, I could serialize the object as JSON or xml and store it in Django's database using a Django Model. Now, my current problem is with filters for a WMS server but this is very similar to what I could have with a set of where clause for a SQL query. So I thought that there might be … -
Django model inheritance: how to retrieve records?
I have these Django models: class Base(models.Model): name = models.CharField(max_length=255) class Restaurant(Base): pass class Hotel(Base) pass class Message(models.Model) text = models.TextField() parent = models.ForeignKey(Base, on_delete=models.CASCADE) I would like to set up a query to retrieve all of the messages left about Hotels only. But how to do that? Message.objects.filter(has_attr("Hotel")) Obviously this doesn't work but something like that is what I am looking for. -
Testing a POST request in Django
I have a function in my Django App that add a product to a favorite database. I need to write a test of it. def add(request): data = {'success': False} if request.method=='POST': product = request.POST.get('product') user = request.user splitted = product.split(' ') sub_product = Product.objects.get(pk=(splitted[1])) original_product = Product.objects.get(pk=(splitted[0])) p = SavedProduct(username= user, sub_product=sub_product, original_product = original_product) p.save() data['success'] = True return JsonResponse(data) I know I have to write something like that: class AddDeleteProduct(TestCase): def setUp(self): User.objects.create(username='Toto', email='toto@gmail.com') def test_add_product(self): old_count = SavedProduct.objects.count() response = self.client.post(reverse('finder:add', { 'product': '12 22' })) new_count = SavedProduct.objects.count() self.assertEqual(new_count, old_count + 1) But I have some trouble passing the datas to the function. My 'product' comes from an AJAX call and I get it from this button value: <div class='sub_button'> <form class="add_btn" method='post'> <button class='added btn' value= '{{product.id }} {{ sub_product.id }}' ><i class=' fas fa-save'></i></button> </div> -
Can't connect Django rest api in AWS live server
I am getting this issue - I have setting with this db configurations - if 'RDS_HOSTNAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } Following this link https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-rds.html I can give python3 manage.py makemigrations command nd runserver command it runs but on migrate command it gives error mentioned above. What should I do? -
HOW DO I INSERT SCRAPED DATA INTO MY DATABASE USING DJANGO WITHOUT DUPLICATES
I scraped some data off the web on the developing pandemic using django, but my problem is that whenever i refresh my app on the browser it inserts same records over and over again into my database and keeps rendering them on my template. # My Model.py class cases(models.Model): states = models.CharField(max_length=20) total_cases = models.CharField(max_length=250) active_cases = models.CharField(max_length=250) discharged = models.CharField(max_length=250) death_cases = models.CharField(max_length=250) date_added = models.DateTimeField(auto_now_add=datetime.now()) def __str__(self): return self.states class Meta: verbose_name_plural = 'Cases' # My view.py states = [] total = [] active = [] discharge = [] death = [] zipped_record = (zip(states,total,active,discharge,death)) # moving records gotten to database def index(request): try: for(state, totals, actives, discharges, deaths) in zipped_record: cases.objects.create(states=state, total_cases=totals, active_cases=actives, discharged=discharges, death_cases=deaths) except: print('Records already exists') context = {'cases': cases.objects.all()} return render(request,'pandemicHome.html',context) # My template <table class="table table-bordered table-striped" id="case_table"> <tr> <th style="font-size: 18px">S/N</th> <th style="font-size: 18px">State</th> <th style="font-size: 18px">Total Cases</th> <th style="font-size: 18px">Active Cases</th> <th style="font-size: 18px">Discharged Cases</th> <th style="font-size: 18px">Death Cases</th> </tr> {% for case in cases %} <tr class="table_rows"> <td style="font-size: 18px">{{forloop.counter}}</td> <td style="font-size: 18px">{{case.states}}</td> <td style="font-size: 18px">{{case.total_cases}}</td> <td style="font-size: 18px">{{case.active_cases}}</td> <td style="font-size: 18px">{{case.discharged}}</td> <td style="font-size: 18px">{{case.death_cases}}</td> </tr> {% endfor %} </table> -
Datetimefield argument
class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) This is from the Django official tutorial. models.DateTimeField('date published') Why is there a string as argument? According to the docs, it seems that DateTimeField does not accept string argument. Thank you for your help. -
DJANGO how to make filter to show all objects in model?
How to change my code so it would show all products in my View? Now it shows only these determined by filters. Please see my code below: def search_product(self, request): search_form = FilterProductForm(request.GET) search_form.is_valid() shape = search_form.cleaned_data.get('shape',[0,1,2]) material = search_form.cleaned_data.get('material',[0,1,2,3]) products = Product.objects.filter(shape__in=shape, material__in=material) return products, search_form -
How to use HttpResponseRedirect in APIView?
I have a hybrid React.js + Django app but still using Django routing. How can I return HttpResponseRedirect instead of a standard DRF response? class DeleteItemAPIView(APIView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsAuthenticated, ) def get_object(self, slug): return get_object_or_404(Item, slug=slug) @transaction.atomic def delete(self, request, slug): item = self.get_object(slug) item.delete() # return Response(status=status.HTTP_204_NO_CONTENT) return HttpResponseRedirect(reverse('items:list')) This is what I see in logs: django_1 | [25/Jun/2020 01:25:11] "DELETE /api/item/delete/2434ad7c-71dd-444f-af81-e568643905e6/ HTTP/1.1" 302 0 django_1 | Method Not Allowed (DELETE): /items django_1 | Method Not Allowed: /items django_1 | [25/Jun/2020 01:25:11] "DELETE /items HTTP/1.1" 405 0 -
Django API with multiple calls using try, except
I am trying to make an API endpoint that will take input like http://127.0.0.1:8000/getslots?car_number=3and give output as car_number or slot_parking. Here is what I have done: slots = {'ka9865': 1, 'ka9866': 2, 'ka9867': 3} def get_car(request): if request.method == 'GET': try: car_number = request.GET['car_number'] for key,value in slots.items(): if key == car_number: car_slot = value response = json.dumps([{'slot': car_slot}]) except (UnboundLocalError): slot = request.GET['car_number'] for key,value in slots.items(): if value == slot: car_number1 = key #not entering inside this loop response = json.dumps([{ 'car_number': car_number1}]) except: response = json.dumps([{ 'Error': 'No car with that name/slot'}]) return HttpResponse(response, content_type='text/json') But I am getting error of UnboundLocalError: local variable 'response' referenced before assignment I am not able to figure out how to do this and also please suggest me if there is any better way of implementing this. Thank you. -
customisation in django admin fields
I know there are similar questions, but answers of none of them work for me, so i am asking for an advice. In my admin.py file i have this code: @admin.register(MyModel) class QRCodeAdmin(admin.ModelAdmin): list_display = ('id', 'user_id', 'name', 'status') search_fields = ('user_id__email', 'name', 'description') list_filter = ('status', 'created_at') In admin panel, list_display fields works fine, when all objects are loaded, but i want when i select certain object and a can see detail view for it, to put description only for 'status' property, hinting what is this property for. How can i do that? -
One to Many relationship real life example
I am trying to design the schema. I am confused about should I use one-to-many or many-to-one relationships. My use case is somewhat like customers ordering the food. There are 2 customers and 5 food items Customers: [John, Alice] Food: [Rice, Noodle, Chicken, Beacon, Ice-cream] Use case: One Customer can order many items, but if first customer orders that item, it can not be ordered by other. Example: John orders -> Rice, Noodle, Chicken Alice orders -> Beacon, Ice-cream **This is valid, both customers ordered unique food.** Example: John orders -> Rice, Noodle, Chicken Alice orders -> Beacon, Ice-cream, Chicken **This is invalid, because Chicken is being ordered twice. John Already ordered chicken so Alice can not order it.** Note: I am trying to this in mongodb documents and trying to establish relationship using Django models. -
Translate django-allauth
I try to translate django-allauth. I create my translation files. But if there are a translate for a sentence in django-allauth, my translate doesn't use. Why this happen? How can I fix it? #: templates/account/logout.html:10 msgid "Are you sure you want to sign out?" msgstr "مطمئنی میخواهی خارج شوی؟" #: templates/account/logout.html:20 msgid "Cancel" msgstr "لغو" In the output I have like this: "Are you sure you want to sign out?" -> the output isn't what I am looking for. there are this sentence in django-allauth. Cancel -> the output is what I am looking for. there aren't this sentence in django-allauth Here is my setting.py: LANGUAGE_CODE = 'fa-IR' USE_I18N = True USE_L10N = True USE_TZ = True LOCALE_PATHS = [ os.path.join(BASE_DIR, 'locale'), ] LANGUAGES = [ ('fa', _('Persian')), ('en', _('English')), ] -
How to fix Django 'utf-8' codec can't decode byte 0xa9 in position 12527: invalid start byte" error
Hello I am new for Django, i developed one simple website to learn. It working fine in local server, recently i tried to deploy that website by using Digital Ocean, then also its working fine. Suddenly i am getting Unicode error. Why this is happening i am not importing any files also is this because of database?, i am using postgress. If any body have solution for this it will be helpful, thanks. here is the error code. Environment: Request Method: GET Request URL: http://139.59.7.210:8080/ Django Version: 2.2.2 Installed Applications: ['homeapp.apps.HomeappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'news', 'yogablog', 'ckeditor', 'social_django', 'spiritual', 'babynames', 'generalnews', 'django_inlinecss', 'timezone_field'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/mesite/djangoprojectdir/djangoprojectenv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/mesite/djangoprojectdir/djangoprojectenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/home/mesite/djangoprojectdir/djangoprojectenv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/mesite/djangoprojectdir/homeapp/views.py" in index 11. return render(request, "index.html", {'slide': slide}) File "/home/mesite/djangoprojectdir/djangoprojectenv/lib/python3.6/site-packages/django/shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "/home/mesite/djangoprojectdir/djangoprojectenv/lib/python3.6/site-packages/django/template/loader.py" in render_to_string 61. template = get_template(template_name, using=using) File "/home/mesite/djangoprojectdir/djangoprojectenv/lib/python3.6/site-packages/django/template/loader.py" in get_template 15. return engine.get_template(template_name) File "/home/mesite/djangoprojectdir/djangoprojectenv/lib/python3.6/site-packages/django/template/backends/django.py" in get_template 34. return Template(self.engine.get_template(template_name), self) File "/home/mesite/djangoprojectdir/djangoprojectenv/lib/python3.6/site-packages/django/template/engine.py" in get_template 143. template, origin = self.find_template(template_name) File "/home/mesite/djangoprojectdir/djangoprojectenv/lib/python3.6/site-packages/django/template/engine.py" in … -
How to sort by presence of value or null with Django ORM
I want to sort a table by two columns. For the first column, I want to sort by the presence of a value or NULL. Unworking code to illustrate what I want to do : MyModel.objects.order_by('blop IS NULL', 'name') I've tried to use annotate but didn't find a way to define an expression to setting a field, or an aggregation function to return a boolean from a field. Unworking code to illustrate what I tried: MyModel.objects.annotate(has_blop=F('blop IS NULL')).order_by('has_blop', 'name') I think i could manage using conditional annotation (Case... When...) but it seems overkill. The database used is postgres. -
Content Security Policy Problems when deploying Django
i want to deploy my django app and for that, in settings.py I set DEBUG=False Since i did that, my website doesn't function anymore and in the Firefox Console, i get tons of error concerning the Content Security Policy. For the last two days i tried to fix this problem but can't seem to get the hang of it. This is my first django project i want to deploy, so it it possible I am missing something obvious. I am using some inline JavaScript and CSS and I am loading my jquery and ajax from googles CDN. I have set the CSP in the header of the base.html page like this: <meta http-equiv="Content-Security-Policy" content="default-src *; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'; img-src * data: 'unsafe-inline'; connect-src * 'unsafe-inline'; frame-src *;"> To test it i made it extremely unsafe, but still none if my scripts want to load. Why is that? The Console logs: Loading failed for the <script> with source “https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js”. account:107:1 Loading failed for the <script> with source “https://cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.js”. account:108:1 Content Security Policy: The page’s settings blocked the loading of a resource at inline (“default-src”). account:18:1 Content Security Policy: The page’s settings blocked the loading of a resource … -
Django admin: Exclude fields in listing but not in editing
I have the following config: class Blog(models.Model): title = models.CharField('Title', max_length=1024, blank=False, null=False) author = models.CharField('Author', max_length=1024, blank=False, null=False) language = models.CharField('Language', max_length=25, blank=False, null=False) content = models.TextField('Content', blank=True, null=True) is_active = models.BooleanField('Active', blank=False, null=False, default=True) class Meta: managed = False db_table = 'blog' verbose_name_plural = "Blogs" class BlogAdmin(admin.ModelAdmin): model = Blog list_display = ('title', 'author', 'language', 'is_active') search_fields = ('title', 'author', 'language') def has_delete_permission(self, request, obj=None): return False admin.site.register(Blog, BlogAdmin) The content field is TextField and huge (up to 200kb). In the list_display option, I haven't added content because of the same reason. But, the SQL query on the listing page gets all the fields and then displays selected. SQL Query (Pagination): SELECT COUNT(*) AS `__count` FROM `blog`; SELECT `blog`.`id`, `blog`.`title`, `blog`.`author`, `blog`.`language`, `blog`.`content`, `blog`.`is_active` FROM `blog` ORDER BY `blog`.`id` DESC LIMIT 100 OFFSET 500; SQL Query (Search): SELECT COUNT(*) AS `__count` FROM `blog` WHERE (`blog`.`title` LIKE '%search_query%' OR `blog`.`author` LIKE '%search_query%' OR `blog`.`language` LIKE '%search_query%'); SELECT COUNT(*) AS `__count` FROM `blog`; SELECT `blog`.`id`, `blog`.`title`, `blog`.`author`, `blog`.`language`, `blog`.`content`, `blog`.`is_active` FROM `blog` WHERE (`blog`.`title` LIKE '%search_query%' OR `blog`.`author` LIKE '%search_query%' OR `blog`.`language` LIKE '%search_query%') ORDER BY `blog`.`id` DESC LIMIT 100; The problem is that the query gets slower (sometimes times … -
Django - How to restrict user for minimum word count in RichTextField - CKEditor?
I'm using Django-ckeditor for content section of my page. I want to restrict the users to write at least 100 letters. I tried with MinLengthValidator, it does restricts but it is not showing any alert. How do I set up this? models.py: from django.core.validators import MinLengthValidator from ckeditor.fields import RichTextField class Post(models.Model): title = models.CharField(max_length=100) content = RichTextField(blank=False, null=True, validators=[MinLengthValidator(100)]) Is there any built-in feature available in django-ckeditor for this? or any better option available? -
How do I render multiple contexts to the same HTML in Django
This is just a question to know about Django. I have two views and I am rendering two contexts to two views.How can I render both the contexts to the same HTML template? -
Django CMS custom plugin
I have this class: class Promotion(models.Model): INACTIVE = 0 ACTIVE = 1 STATUS = ( (INACTIVE, 'Inactive'), (ACTIVE, 'Active'), ) title = models.CharField(max_length=100) image_carousel = models.ImageField( upload_to='promotii/carousel/', null=True, blank=True) image_promotion = models.ImageField( upload_to='promotii/', null=True, blank=True) status = models.BooleanField(default=0, choices=STATUS) slug = models.SlugField(max_length=100) partners = models.ManyToManyField(Partner, related_name='partners', blank=True) def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super().save(*args, **kwargs) def get_absolute_url(self): kwargs={"slug": self.slug} return reverse('promotii', kwargs=kwargs) I want to create a custom plugin for Promotion model. If there is an active promotion my idea is that the user can add a carousel-item to the carousel, witch also renders the image (image_carousel field), and a link on the image based on the slug field ex. /promotii/<slug_field>. I am new in django cms, there is any solution for this problem? -
How can I troubleshoot PCs not seeing each other over my LAN
I'm a complete newbie when it comes to networking. I have two PCs on my LAN both running Manjaro. My main aim is to test functionality on a Django server running on one PC, from the other. I am running the Django server on the PC with ip address 192.168.1.138 using the command python manage.py runserver 192.168.1.138:8000 and in settings.py ALLOWED_HOSTS = ['localhost', '192.168.1.138'] I can ping 192.168.1.138 from the client PC, but if I enter the ip address/port into the browser, it fails with took too long to respond I don't know if this a separate problem or a manifestation of the first, but when I run NitroShare, I am able to 'see' the PC running the Django server from the PC acting as the client, but if I try to transfer a file, again it times out. I am unable to see the client from the server in NitroShare. Any suggestions or help gratefully received -
Media file not loading from server in django 3.0
i have hosted the django project but my media files are not loading so far i have tried to change the location of media url but it is not working and while clicking the path of image ,page not found Settings.py BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_URL= '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) template {% for i in slides %} <img class="bd-placeholder-img sliding" width="100%" height="100%" src="{{i.imag.url}}" preserveAspectRatio="xMidYMid slice" focusable="false" role="img"> i have tried /media/{{i.imag.url}} but imag is not loading although in local server image is loading in /media/{{i.imag}} in this url but not in server while inspecting <img class="bd-placeholder-img sliding" width="100%" height="100%" src="/media/" role="img"> how to solve it? thank you for your time -
Integrate Django app into kibana on different server
I currently have a django app running on server1 and there is shared kibana elk already setup on server2. Can someone pls suggest how to integrate django app logs present on server1 to kibana present on server2? -
how can we retrieve documents saved in binary format in postgresql using djnago and python
I have uploaded image and documnets in postgresql using django models : ''' class ConsolePicture(models.Model): #filemodel bytes = models.TextField() filename = models.CharField(max_length=255) mimetype = models.CharField(max_length=50) class ConsolePdf(models.Model): #filemodel bytes = models.TextField() filename = models.CharField(max_length=255) mimetype = models.CharField(max_length=50) class Console(models.Model): name = models.CharField(max_length=100) picture = models.ImageField(upload_to='first_app.ConsolePicture/bytes/filename/mimetype', blank=True, null=True) docfile=models.FileField(upload_to='first_app.ConsolePdf/bytes/filename/mimetype',blank=True,null=True)''' After this files are saved in postgresql but in binary format . Now how can i retrieve and display the stored files in django webpage? -
django Microsoft SQL server migrate issue django.db.migrations.exceptions.MigrationSchemaMissing
below is the error i am facing when doing python manage.py migrate after connecting to MicrosoftSQL Server database in Django framework. not able to do migrate and work with that data base error: ```django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]The specified schema name "dbo" either does not exist or you do not have permission to use it. (2760) (SQLExecDirectW)'))`` -
Django Allauth Recaptcha V3 Validation With Content Security Policy
I would like to validate recaptcha v3 on allauth's forms without overriding allauth's views.py and do the validation from within my app if possible. I tried django-recaptcha package and can't use it because the scripts cannot be overridden to have a django-csp nonce value <script nonce="{{request.csp_nonce}}">. I think django-recaptcha3 should be able to add a nonce value to the recaptcha scripts so this package should probably be used to do this. Otherwise, I am fine with something else. I will end up adding the same recaptcha validation code for all the other allauth forms. But the example below only shows the login view while the forms.py has all of the forms ready to go. I am not confident with the views.py code. I don't have a way to test it to see if it worked or not. I also am not fluent in javascript and am not sure how to add a token refresh after it expires. Views.py (With Allauth Login Example): import json import urllib def MyLoginView(request, LoginView): form = CaptchaLoginForm() if request.method == 'POST': form = form = CaptchaLoginForm(data=request.POST) if form.is_valid(): recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' payload = { 'secret': SECRET_KEY, 'response': recaptcha_response } data = urllib.parse.urlencode(payload).encode() …