Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
BaseInFilter separates values by comma. What if a value has a comma?
I am using BaseInFilter and it works great. I am able to have URLs like /producs/?title=some_title,some_other_title. But what if a title has a comma? Can I somehow encode it? Or the only way for me to use ids (which I really really do not want to do because of SEO and readability). Thanks. -
Django Custom Function in Admin site
I usually upload videos using aa admin site. But I want to download the video automatically from url and upload it automatically. So I created a phtube function, but I don't know how to make it apply when I click Save on the admin page. my amdin site of videos and it's my veiws.py plz help me thanks class Video(models.Model): url = models.CharField(max_length=255, blank=True) title = models.CharField(max_length=255) video = models.FileField(upload_to='videos/%Y/%m/%d/', blank=True) thumbnail = ProcessedImageField( default='videos/default/image.png', upload_to='videos/%Y/%m/%d/', processors = [ResizeToFill(520, 440)], format = 'JPEG', options = {'quality':70}) created_at = models.DateTimeField(auto_now_add=True) tag = models.CharField(max_length=255, null=True, blank=True) def pytube(self): if self.url is not None: yt = YouTube(url) self.title = yt.title self.video = yt.streams.first().download('C:/Users/che99/Downloads/', title) self.thumbnail = urllib.request.urlretrieve(yt.thumbnail_url,'title.jpg') def filename(self): return os.path.basename(self.file.name) # https://stackoverflow.com/questions/38257231/how-can-i-upload-multiple-files-to-a-model-field def __str__(self): return self.title + ' : ' + str(self.tag) -
Pip Not recognized as an external command in cmd in windows
When i am trying to install the Python 3.7.1 it installs and i am also check the pip install check box and installed.Later i am trying to install pip in cmd This error is occurred. When i am going to see the pip.exe file in Python37/Scripts it shows empty folder. I don't know what to do and what is the issue -
Facebook API For Getting Track Of Profiles You Visited
I want to get a track record of all the profiles i visited on a particular day on Facebook and accordingly graph it. So can I get a API which gives me the record of all the profiles i visited on a particular day. -
tabular inline admin where table are referenced in multiple tables
I was looking on customizing admin where i found tabularinline model which allow us to edit on the same page. But i got confused as my tables are reference in multiple places. I could not understand which model should i make tabular inline. for example here is my model class ProductType(ModelWithMetadata): name = models.CharField(max_length=150, help_text="type of product. ex - accessories, apparel") slug = models.SlugField(max_length=150, unique=True) is_shipping_required = models.BooleanField(default=True) class Meta: ordering = ("slug",) app_label="products" class Category(MPTTModel, ModelWithMetadata): name = models.CharField(max_length=128) slug = models.SlugField(max_length=128) description = models.TextField(blank=True) parent = models.ForeignKey( "self", null=True, blank=True, related_name="children", on_delete=models.CASCADE ) objects = models.Manager() tree = TreeManager() class Meta: verbose_name = "Category" verbose_name_plural = "Categories" def __str__(self): return self.name class Product(ModelWithMetadata, PublishableModel): product_type = models.ForeignKey( ProductType, related_name="products", on_delete=models.CASCADE ) name = models.CharField(max_length=128) slug = models.SlugField() category = models.ForeignKey( Category, related_name="products", on_delete=models.SET_NULL, null=True, blank=True, ) isAvailable = models.BooleanField(default=True) isDiscount = models.BooleanField(default=False) charge_taxes = models.BooleanField(default=False) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: verbose_name = "product" verbose_name_plural = "products" ordering = ("name",) constraints = [ models.UniqueConstraint( fields=["article_number", "slug"], name="unique article number and slug") ] class ProductVariant(ModelWithMetadata): sku = models.CharField(max_length=255, unique=True) name = models.CharField(max_length=255, blank=True) currency = models.CharField( max_length=settings.DEFAULT_CURRENCY_CODE_LENGTH, default=settings.DEFAULT_CURRENCY, blank=True, null=True, ) price_override_amount = models.DecimalField( max_digits=settings.DEFAULT_MAX_DIGITS, decimal_places=settings.DEFAULT_DECIMAL_PLACES, blank=True, null=True, ) … -
preventing access to particular url / view
I'm currently using twilio on my web application. I've setup a counter that increments by 1 for every incoming sms request. If the counter hits 100, I want to prevent twilio from being able to access the webhook url that I've setup on twilio. 100 hits in a given day is indicative of abuse and if twilio isn't able to make contact with the webhook url that I've set in the twilio configuration, I won't be charged for any subsequent sms messages that are being sent to my number by the attacker. What's the best way to make twilio fail to be able to connect to my url? I've run http reponses of 404 and created a decorator that refuses access if the limit is hit, and twilio does report errors on these attempted requests, but they still count as 'received' and thus, I get charged for them. What the best way of causing twilio to fail to connect to my webserver after the counter exceeds X? Thanks! -
Python convert rtf into html
How can convert a rtf string into html usign python. For more clarification I have a django app which use ckeditor to store html template in django model.In my view when I fetch the template for sending email.However instead of getting html string i am getting rtf string. My model class ETemplate(models.Model): template_name = models.CharField(max_length=255,unique=True) template_subject = models.CharField(max_length=500) template_body=RichTextUploadingField() template_type= models.CharField(choices=TEMPLATE_TYPE,default='email',max_length=500) -
cant sign in user, not getting the right response, trying to get user with token
Im having a lot of problems in my first django, rest-framework application. here is a link to the code: github pages Im not getting the token after Im signing up, instead of "user" : { "_id":"1", "username":"you", "email":"a@a.com" }, "token" : 'fjdjfkljgkghgjkl' } Im getting { "_id":"1", "username":"you", "email":"a@a.com" } what could be the problem here? When Im trying to sign in, postman tells me: {"username" :["user with this username already exist.]} and Im trying to sign in not sign up. why is this happening? When Im trying to get all the todos that belongs to the user I get this error: {"details":"Authentication credantials were not provided" } , instead of an empty list, why is that? how can I get the user if I have only the token? here is a link to the code: github pages -
Create A Many-To-Many Relationship In A Test
I have a many-to-many relationship: class Person(models.Model): modules = models.ManyToManyField(BaseModule, blank=True) class BaseModule(models.Model): task_type = models.CharField(max_length=200) topic = models.CharField(max_length=200) I am loading in my fixtures test data, populating my 'BaseModule' database: fixtures = ['test/fixtures/initial_data.json'] Then creating a User object, but I cant figure out how to create a relationship between a User and BaseModule. Ive tried many things, including: # this works, but creates a new BaseModule, I want to create a relationship with one generated in 'fixtures' test = person.individual_modules.create(topic='test') test.save() # this doesnt work testModule = BaseModule.objects.get(pk=1) person.individual_modules.set(testModule) # this doesnt work either person.individual_modules.create() person.individual_modules.basemodule_id = 1 person.refresh_from_db() for module in person.individual_modules.all(): print("module.topic:") print(module.topic) print("end") Thank you. -
can you use css on pycharm for django development
I'm following some django tutorials and i need to use css on my projects but pycharm doesn't recognise it so i downloaded css package at project interpreter, but i think it's not recognising it again. I get this error on the web page: 'styles.css' could not be found and this is how my project structure looks like -
How to Convert DateTime to String in Django/DRF While Testing
I'm testing an endpoint which naturally returns a JSON containing the datetime as a string. I compare the response content in test as such: assert serializer_instance.data == { "created_at": str(model_instance.created_at), "updated_at": str(model_instance.updated_at), } created_at and updated_at are surely DateTimeFields. However, in this case, test fails saying: E Differing items: E {'created_at': '2020-06-24T12:42:03.578207+03:00'} != {'created_at': '2020-06-24 09:42:03.578207+00:00'} E {'updated_at': '2020-06-24T12:42:03.578231+03:00'} != {'updated_at': '2020-06-24 09:42:03.578231+00:00'} So str uses a different formatting on datetimes. Sure, the test case can be passed successfully using strftime, but there should be an internal function that does it easily in either Django or Django Rest Framework and I'd like to learn it. Thanks in advance. Environment Python 3.8.3 Django 2.2.12 Django Rest Framework 3.11.0 -
Apply ajax to dropdown which is in the same row in table
I have a table consisting of many rows in which I have select fields, now I want to make changes to second dropdown based on first dropdown which is in the same row of the table and not all the dropdowns in table. <table class="table table-striped table-hover mb-0 table-bordered"> <thead> <tr> <th>Dropdown 1</th> <th>Dropdown 2</th> </tr> </thead> <tbody> <tr> <td> <select class="form-control" id="client" required name="client"> <option value="">Select Client</option> {% for client in client %} <option value="{{ client.name }}">{{ client.name }}</option> {% endfor %} </select> </td> <td> <select class="form-control" id="job" required name="job"> </select> </td> </tr> ... </tbody> </table> Ajax Code: <script> jQuery("#client").on('change',function (e) { e.preventDefault(); jQuery.ajax({ type:'POST', url:'{% url 'createWorks' %}', dataType:'json', data: jQuery("#myform").serialize(), success: function (data) { $('select[name=job]').empty(); $('select[name=job]').append('<option value="' + '' + '">' + 'Select Job' +'</option>'); for(let job of data['job']){ $('select[name=job]').append('<option value="' + job['job'] + '">' + job['job'] +'</option>'); } } }); }); </script> I have used select[name=job] so it is making changes in every dropdown whose name=job but I want to make changes in the dropdown which is adjacent to first dropdown. I have tried using const row = $(this).closest('tr'); -
Render django's Multiwidget & MutliValueField Textarea using Crispy Forms
I have a TextField intended to store a large amount of text that can be logically split into 10 parts. I thought that it would make sense to create 10 separate Textareas, each for one logical part. Thus, I subclassed MultiWidget and MultiValueField like so: class MultiWidget(forms.widgets.MultiWidget): template_name = "custom_content_widget.html" attrs = {"class": "textarea form-control"} def __init__(self, attrs=None): widgets = [Textarea()] * 10 super(MultiWidget, self).__init__(widgets, attrs) def decompress(self, value): if value: return value return ["", "", "", "", "", "", "", "", "", ""] class ContentField(MultiValueField): widget = MultiWidget def __init__(self, *args, **kwargs): # Define one message for all fields. error_messages = { 'required': 'This field is required.', } # Or define a different message for each field. fields = [CharField()] * 10 super(ContentField, self).__init__( error_messages=error_messages, fields=fields, require_all_fields=True, *args, **kwargs) # self.helper = FormHelper() # self.helper.layout = Layout( # # ) def compress(self, data_list): return " ".join(data_list) with the custom_content_widget.html being just {% for subwidget in widget.subwidgets %} {% with widget=subwidget %} {% include widget.template_name %} {% endwith %} {% endfor %} Simple model and form in which I'd like to use this multiwidget class Opinion(models.Model): content = models.TextField() class OpinionForm(forms.ModelForm): content = ContentField() class Meta: model = Opinion fields … -
Django form not saving if I use action attribute
For context, here is the view.py from .forms import SignIn ... def sign_in_view(request, *args, **kwargs): form = SignIn(request.POST or None) if form.is_valid(): form.save() form = SignIn(request.POST or None) context = { 'form': form } return render(request, "accounts/sign_in.html", context) here is the HTML file for accounts/sign_in.html {% extends "accounts/base.html" %} {% block title %} <title>Log-in</title> {% endblock %} {% block content %} <h1 align="center">Sign in</h1> <hr/> <form method="POST" action="http://127.0.0.1:8000/home/"> # currently in localhost {% csrf_token %} {{ form.as_p }} <input type="submit" value="Sign in"> </form> {% endblock content %} Without the attribute action="http://127.0.0.1:8000/home/" in my form tag in accounts/sign_in.html, I manage to successfully add a user to the database by typing in the required parameters on the browser. However, with the attribute action="http://127.0.0.1:8000/home/", I was redirected to the URL, but when I checked the database in /admin/, I was unable to see the user there. I don't know if the form isn't saved, or I had just done some stupid mistake. Thanks. -
Array inside django model
I'am new to Django framework, and can't realize this Here is the template I show you what should be posted from template function addProduct() { var table = document.getElementById("ProductTable"); var row = table.insertRow(1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); cell1.innerHTML = ` <div class="form-group"> <select class="form-control" > <option value="1">Smartphone</option> <option value="2">Smart TV</option> <option value="3">Laptop</option> <option value="4">Desktop</option> <option value="5">Sofa</option> <option value="6">Bicycle</option> </select> </div> `; cell2.innerHTML = ` <div class="form-group"> <select class="form-control" > <option value="1">3 months</option> <option value="2">6 months</option> <option value="3">12 months</option> <option value="4">24 months</option> </select> </div> `; } <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> <div class="container"> <div class="row"> <div class="col-md-12 p-4"> <div class="form-group"> <label for="c_name">Customer name:</label> <input class="form-control" id="c_name" type="text"> </div> <div class="form-group"> <label for="c_phone">Customer phone:</label> <input class="form-control" id="c_phone" type="tel"> </div> </div> <table class="table table-bordered" id="ProductTable"> <thead> <tr> <th>Product name:</th> <th>Installment period:</th> </tr> </thead> <tbody> <tr> <td> <div class="form-group"> <select class="form-control" > <option value="1">Smartphone</option> <option value="2">Smart TV</option> <option value="3">Laptop</option> <option value="4">Desktop</option> <option value="5">Sofa</option> <option value="6">Bicycle</option> </select> </div> </td> <td> <div class="form-group"> <select class="form-control" > <option value="1">3 months</option> <option value="2">6 months</option> <option value="3">12 months</option> <option value="4">24 months</option> </select> </div> </td> </tr> </tbody> <tfoot> <tr> <td colspan="2" class="text-center"> <button class="btn btn-success" onclick="addProduct()">add new product</button> </td> </tr> </tfoot> </table> </div> </div> Here is … -
: 'endblock', expected 'else' or 'endifequal'. Did you forget to register or load this tag?
Here is my code: {% extends 'navigationbar.html' %} {% block body %} {% ifequal error "no" %} <script> alert('Logged in successfully') window.location=('{% url 'home' %} ' ); </script> {% ifequal error "yes" %} <script> alert('Invalid Login credentials'); </script> {% endifequal %} <div class="container" style= "margin-top:60px" > <h2 class="text-center text-danger font-weight-bold"> Admin Login </h2> <form method="post"> {% csrf_token %} <label> <b> Admin name</b></label> <input type="text" name="uname" class="form-control"> <label> <b> Password</b></label> <br> <input type="password" name="pwd" class="form-control"> <br> <input type="submit" value="login" class="form-control btn btn-danger"> </form> </div> {% endblock %} i cant seem to find any error but still it shows that invalis syntax can anybody help find the solution. even the tags have no space between { and %. -
Need a partnership with a Web application
I didn’t know where to post this message, please forgive me, if I’ve done mistake by posting this message here. I am working at a non-profit educational organisation. Due to corona crises and less budget, unfortunately our city’s mayor has decided that either we must pay fee or he will close our organisation. Therefore, I’ve decided to make a web application (online campaign) for voting. What does this app do? It is only one page. The visitors read and start voting (yes | no). Before voting, the app sends a verification email. By clicking this link, he/she can start voting. If the email is from our server, stores the votes in a data table (our_member_table). if not, stores the votes in another table (guest_table). This application has one donation with max 1$. This application will be active for a couple of months and in my own server (IIS). Its data storage type will be SQLite with two tables (our_members and guest), which I can write it. What I need? A developer, who can write this app but doesn’t matter which language. What do you get? As I wrote, it is non-profit organisation. We don’t work for money. If you want, … -
How to make an alias of a method?
I have a model class MyModel and I'm very often doing a filter() on it like MyModel.objects.filter() I would like to make a generic class with a method .f() that calls .objects.filter() (some kind of alias) without loosing any cpu time. class BaseModel(models.Model): def f(self): return # ? what should I put here to call .objects.filter() of the descendants? So my call is changed from MyModel.objects.filter() to MyModel.f(), much shorter (but still understandable IMHO). -
Django - How to create a dictionary containing every word of a TextField
How do I go about transforming a Django TextField into a dictionary containing all the words in the field? I've tried the following, but it doesn't seem to work (no errors, but don't see anything in my template or the shell): def song_words(): result = Song.objects.filter(pk=request.pk).values_list('lyrics_ru',flat=True) r_list =[] for r in result: r_list.append(r.split()) return r_list I also tried: def get_word(self): dict_value = getattr(self, 'lyrics_ru_dict', None) if not dict_value: import json dict_value = json.loads(self.lyrics_ru) setattr(self, 'lyrics_ru_dict', dict_value) return dict_value def set_word(self, new_lyrics_ru): import json self.lyrics_ru = json.dumps(new_lyrics_ru).encode('utf8') self.lyrics_ru_dict = dict(new_lyrics_ru) word = property(get_word, set_word) But I get the following error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). I don't have any experience with json, and I have no idea if this is the right way to go. This is my model: class Song(models.Model): title = models.CharField(max_length=25) artist = models.CharField(max_length=25) url = models.URLField() lyrics_ru = models.TextField(max_length=1500) lyrics_gb = models.TextField(max_length=1500) def __str__(self): return self.title My end goal is that I want to compare the words contained in lyrics_ru with the words (specifically, target_word) in a different model: class Word(models.Model): target_word = models.CharField(max_length=25) source_word = models.CharField(max_length=25) The problem is that I have no idea whether I am on the right track or … -
retrieve database values and display in piechart
I am creating a website using python and Django. I want to display the data in pie chart. As of now, i have made it as static. But now i want to retireve my mongodb values and display it in pie chart. Here's my HTML code: <body> <div id = "container" style = "width:100%; height:100%"></div> <script> anychart.onDocumentReady(function() { var data = [ {x: "White", value: 223553265}, {x: "Black or African American", value: 38929319}, {x: "American Indian and Alaska Native", value: 2932248}, {x: "Asian", value: 14674252}, {x: "Native Hawaiian and Other Pacific Islander", value: 540013}, {x: "Some Other Race", value: 19107368}, {x: "Two or More Races", value: 9009073} ] var chart = anychart.pie(); chart.title("Current Shift Defect %") chart.data(data); chart.container('container'); chart.draw(); // set legend position chart.legend().position("right"); // set items layout chart.legend().itemsLayout("vertical"); chart.sort("desc"); }); </script> -
Put a constraint on an attribute of a related model
I have two models: Account and Transfer. The model Account has the attribute currency (EUR, USD, JPY, etc.). The model Transfer has two attributes account_from and account_to. I want to add a constraint that checks that account_from uses the same currency as account_to. I was thinking of adding such a constraint on Transfer model: class Meta: constraints = [ CheckConstraint(check=Q(account_from__currency=F('account_to__currency')), name='same_currency'), ] But that doesn't work because of error django.core.exceptions.FieldError: Joined field references are not permitted in this query How do I do that ? Without relying on SQL. I know how to do that in SQL but I want to use the ORM. Or is it impossible to do that with Django ORM ? -
How can I package django with web-socket server using PyInstaller?
I have a django app, that uses web socket to communicate with different modules and it also starts with arguments. I modified the manage.py file to make it work with arguments as it is one of my modules. The structure of django stayed the same, only manage.py was modified. This is manage.py file. if __name__ == "__main__": # TMS configuration tmsIp = None tmsPort = None # Database configuration dbIp = None dbPort = None db_name = None db_user = None db_user_password = None ENVIRONMENT_DB_NAME = '' ENVIRONMENT_DB_USER = '' ENVIRONMENT_DB_PASSWORD = '' db_name = os.environ.get(ENVIRONMENT_DB_NAME) if db_name is None: raise Exception("Database name was not found in environment variables") db_user = os.environ.get(ENVIRONMENT_DB_USER) if db_user is None: raise Exception("Database user was not found in environment variables") db_user_password = os.environ.get(ENVIRONMENT_DB_PASSWORD) if db_user_password is None: raise Exception("Database password was not found in environment variables") parser = argparse.ArgumentParser() parser.add_argument("--tmsIp", help="TMS server IP used to run messaging server on") # Server port can be set using this parameter parser.add_argument("--tmsPort", help="TMS server port used to run the messaging server on") # Database IP parser.add_argument("--dbIp", help="Database ip") # Database Port parser.add_argument("--dbPort", help="Database port") # Display version parser.add_argument('--version', help="Displays the version of the module", action='store_true') args = parser.parse_args() … -
Do schedulers slow down your web application?
I'm building a jewellery e-commerce store, and a feature I'm building is incorporating current market gold prices into the final product price. I intend on updating the gold price every 3 days by making calls to an api using a scheduler, so the full process is automated and requires minimal interaction with the system. My concern is this: will a scheduler, with one task executed every 72 hrs, slow down my server (using client-server model) and affect its performance? The server side application is built using Django, Django REST framework, and PostgresSQL. The scheduler I have in mind is Advanced Python Scheduler. -
TypeError: object of type 'bool' has no len() i cant find problem
i get TypeError: object of type 'bool' has no len in django admin models models.py user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=False, null=False) slug = models.CharField(max_length=50, blank=True, null=True) default_image = models.ImageField(upload_to='products', blank=False) stock = models.IntegerField(blank=False, null=False) brand = models.ForeignKey(ProductBrand, on_delete=models.CASCADE) price = models.CharField(max_length=15, blank=True, null=True) on_sale = models.BooleanField(default=False) createAt = date.jDateField(auto_now_add=True, editable=False) description = models.TextField(max_length=250, blank=True, null=True) small_description = models.TextField(max_length=150, blank=True, null=True, ) variableProduct = models.BooleanField(default=False) category = models.ManyToManyField(Category, default=False, blank=True) productTags = models.ManyToManyField(ProductTags, default=False, blank=True) admin.py class ProductsModelView(admin.ModelAdmin): formfield_overrides = { models.TextField: {'widget': Textarea(attrs={'dir': 'rtl', })}, } model = Products list_display = ('name', 'id', 'username') admin.site.register(Products, ProductsModelView) Error TypeError at /admin/products/products/add/ object of type 'bool' has no len() Request Method: POST Request URL: http://192.168.1.199:8000/admin/products/products/add/ Django Version: 3.0.7 Exception Type: TypeError Exception Value: object of type 'bool' has no len() Exception Location: E:\GOA\GOA\venv1\lib\site-packages\django\forms\models.py in has_changed, line 1354 Python Executable: E:\GOA\GOA\venv1\Scripts\python.exe Python Version: 3.7.7 Python Path: ['E:\\GOA\\GOA', 'C:\\Users\\pc\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip', 'C:\\Users\\pc\\AppData\\Local\\Programs\\Python\\Python37\\DLLs', 'C:\\Users\\pc\\AppData\\Local\\Programs\\Python\\Python37\\lib', 'C:\\Users\\pc\\AppData\\Local\\Programs\\Python\\Python37', 'E:\\GOA\\GOA\\venv1', 'E:\\GOA\\GOA\\venv1\\lib\\site-packages', 'E:\\GOA\\GOA\\venv1\\lib\\site-packages\\setuptools-40.8.0-py3.7.egg'] Server time: Wed, 24 Jun 2020 08:11:15 +0000 i try to save object in django admin and i get this error but create object in python shell has no problem -
Is there a way to render large querysets in Django templates as the query is populated?
I have a queryset that is rather large and a server thats really slow. When im rendering my template, I noticed that the page only renders after the queryset has been populated. In order to increase the speed of the page loading, I am thinking that maybe my page can render the queryset on the fly as the queryset is being filtered but im not sure if there is an implementation like this in Django. My queryset has well over 1000 items that have roughly 20 attributes each and i need to show all of them on the page. I tried playing around with my Handsontable render but I discovered that the time taken is to actually run the queryset filter and not so much the handsontable render. If anyone could help point me in the right direction , it will be greatly appreciated