Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to define MEDIA location when using django-tenants?
I am using django-tenants and I want to have folder for every tenant MEDIA files, but at the moment it is OK for me to have shared static files. My settings part for STATIC and MEDIA: STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = "/media/" DEFAULT_FILE_STORAGE = "django_tenants.files.storage.TenantFileSystemStorage" # MULTITENANT_RELATIVE_MEDIA_ROOT = "" # (default: create sub-directory for each tenant) MULTITENANT_RELATIVE_MEDIA_ROOT = "%s" So, in views I tried to define location as I did before without django-tenants: file_location = settings.MEDIA_ROOT + image.svg This would work, but it just drops the file to: 'C:\\Users\\PcUser\\Documents\\GitHub\\ProjecName\\media/image.svg' Without tenant subfolder... I tried to do it this way: file_location = settings.MULTITENANT_RELATIVE_MEDIA_ROOT + image.svg But it would save to: '%s/image.svg Maybe I should get the schema name from request and just add the folder in views.py? What would be the right way? Documentation is not really clear on this part, and I cannot put together any concept in my head. Could any one help me out? Thanks! -
onchange function doesn't work with some fields
This funtion is to show the product price when i choose a product from a dropdown list. I'm working on django project, when a 'price_buy' field is set to DecimalField on models, this function doesn't work, but if FloatField, it works fine. Also if another field is None, i get this error msg (Uncaught ReferenceError: None is not defined at HTMLSelectElement.select.onchange ((index):552)). How i can resolve this problem ?. <script type="text/javascript"> document.querySelectorAll("select").forEach((select) => { select.onchange = function(){ var price_buy = 0; const value = this.value; {% autoescape off %} const products = {{ products }} {% endautoescape %} for (var index=0; index < products.length; index++ ) { if (products[index].id == value) { price_buy = products[index].price_buy; } } const name = this.name.replace("product", "price_buy") console.log(price_buy, name); document.querySelector(`input[name=${name}]`).value = price_buy; } }); </script> Django Model: class Product(models.Model): name = models.CharField(max_length=64) price_buy = models.DecimalField() production = models.FloatField(blank=True, null=True) -
Change representation of Superclass without field depending of Subclass object (__str__)
I am running a django app and have a setup like this: ModelSuper(models.Model): class Meta: abstract = False ModelSub1(ModelA): name = models.CharField(...) def __str__: return self.name ModelSub2(ModelA) name = models.CharField(...) def __str__: return self.name ModelForeign(models.Model): element = models.ForeignKey(ModelA) def __str__: return self.name So ModelForeign has a FK to ModelSuper. What happens now is that when I create an instance of ModelForeign I can choose if it belongs either to ModelSub1 or to ModelSub2. But the string representation is ModelSuper Onject (3) where (3) is the id. Normally I can change this representation by overwriting the __str__ method on the model, but since I do not have any fields on the Supermodel I can't return anything. What I tried: I have already implemented the __str__ method in the Submodels but that does not help. I wanted to make the Super model abstract. But this does not let me point FKs to the Supermodel, so I can't do this. My setup requires this FK I used a generic FK with django's ContentType framework. This is also not an option because it messes completely with my app and is also not recommended from an SQL perspective. Also when I do API-calls I get … -
Page not found at /register using restframework
so i'm building a simple auth system using restframework and i got this error using postman : Page not found at /register i guess i need to provide only urls.py from the app from django.urls import path from .views import RegisterView urlpatterns = [ path('/register',RegisterView.as_view(),name="register") and here is urls from main app from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('/',include('useraccounts.urls')) ] -
Django ORM error: UnicodeDecodeError: 'utf-8' codec can't decode byte
When I use SomeModel.objects.get(id=), I get this exception: UnicodeDecodeError: 'utf-8' codec can't decode byte... As I see that field comment (type TextField) of this object has a german word. But SomeModel.objects.get(id=) works well with english words -
Why use React with Django?
What is the advantage of using Django with React instead of just Django, where you hit the DB and render the information, style it with CSS and HTML? Is it Performance/scalability/maintenance?? I see a lot of React and Django projects but don't understand the necessity of React for a small/medium sized business? I mean, if you want some async tasks you could just use AJAX, right? -
QuerySet has no field_names?
So I'm currently upgrading a Django app from 1.8 to 3.1 and came upon the following error: AttributeError: 'QuerySet' object has no attribute 'field_names' I have tried to find deprecation information on this attribute and checked the QuerySet API for information but couldn't find anything relevant. Has anybody gone through the same? -
How to make full page tabs, that act individually?
Sorry I'm showing a lot of code but I cant convey my meaning well enough. So my first page works perfectly, you type in a URL, information from that product shows up then the user clicks it then the name of the product become the tab name and the url path. I want to make this work with tabs where each time you press a new tab it takes you to the starter page and each tab acts as an individual page. How could I do this using JavaScript. HTML <!DOCTYPE html> <html> <head> <title> </title> </head> <body> <!DOCTYPE html> <html> <head> <title> </title> </head> <body> <!-- Required meta tags --> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport"><!-- Bootstrap CSS --> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"> <link href="/static/homepage/main.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script> <header> <link href="/static/homepage/main.css" rel="stylesheet" type="text/css"> <div class="tabcontainer" id="tabcon" style="background-color: aquamarine"> <ul id="navigation1"> <li class="tabli" id="button1"><button class="tabs" onclick="window.location.href='#page1'" >tab 1</button></li> <ul id="navigation2"> <li id="tabli"> <button onclick="newTab()" class="addbut" style="text-align: center"> + </button> </li> </ul> </ul> </div> </div> <div id="smallSearch"> </div> <script src="https://cod'e.jquery.com/jquery-3.2.1.slim.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"> </script> <div class="container"> <script src="//cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.js"> </script> <link href="//cdnjs.cloudflare.com/ajax/libs/dygraph/2.1.0/dygraph.min.css" rel="stylesheet"> <div class="containFORM" id="containFORM"> <form id="myForm" method="post" name="myForm" onkeydown="return … -
How to change Uniqueconstrain error to a custom one?
here is an example of a model with Uniqueconstrain class Volume(models.Model): id = models.AutoField(primary_key=True) journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal") volume_number = models.CharField('Volume Number', max_length=100) comments = models.TextField('Comments', max_length=4000, blank=True) class Meta: constraints = [ models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint') ] -
Recreate applied migration in Django
I have a situation where on an important environment for my application a migration file was generated with the latest code changes and applied to the database. Since there were several changes on the models the name was auto generated with a timestamp. Unfortunately the file was lost after that and not committed to a version control system. Now I'm pretty sure that using the same version from which this migration file was created I can recreate exactly the same migration file, but it will carry different name (with different timestamp) and will cause Django to fail (since the migration removes a table). In this situation where I know the newly generated file is matching the one that is lost but applied to the DB can I just rename the new file to match the name of the one that was applied - so that Django can recognise the migration as applied? I'm not sure how Django evaluates applied migrations and recognising the files.. Is it only by the name of the file like it is stored in the migration history table? Also is there a better solution from the one I'm thinking about? -
Explicitly fields aren't returned in serializer in django-rest-framework
I'm trying to get a serializer of a model with a field from another model wich are related by a foreing key relation. The desired result should be: "coordinates": [ { "coordinate": "42.0677", "coordinate_type": "shooting_latitude" }, { "coordinate": "-8.0990", "coordinate_type": "shooting_longitude" } ] And the models are: class CoordinatesType(models.Model): coordinate_type = models.CharField(max_length=100, null=False, blank=False) coordinate_description = models.TextField(null=False, blank=False) class Coordinates(models.Model): coordinate_type = models.ForeignKey('hauls.CoordinatesType', null=False, blank=False, on_delete=models.CASCADE) coordinate = models.DecimalField(max_digits=10, decimal_places=4, null=False, blank=False) I can do it whit a nested serializer: class CoordinatesTypeSerializer(serializers.ModelSerializer): class Meta: model = CoordinatesType fields = ['coordinate_type'] class CoordinatesSerializer(serializers.ModelSerializer): coordinate_type = CoordinatesTypeSerializer(read_only=True) class Meta: model = Coordinates fields = ['coordinate', 'coordinate_type', ] In this case, the result of the serializer is: "coordinates": [ { "coordinate": "42.0677", "coordinate_type": { "coordinate_type": "shooting_latitude" } }, { "coordinate": "-8.0990", "coordinate_type": { "coordinate_type": "shooting_longitude" } } ] And then I could override the to_representation() method to avoid the nesting data and get the desired result. But, in this case with only one nested field, I think it could be simpler create an explicit field and I tried: class CoordinatesSerializer(serializers.ModelSerializer): coordinate_type = serializers.CharField(read_only=True, source="coordinatestype.coordinate_type") class Meta: model = Coordinates fields = ['coordinate', 'coordinate_type', ] But looks like the serializer ignore the explicit field … -
Django GraphQL JWT: tokenAuth mutation returns "str object has no attribute decode"
Currently I'm running a basic example of django-graphqljwt from the documentation page. https://django-graphql-jwt.domake.io/en/latest/quickstart.html import graphene import graphql_jwt class Mutation(graphene.ObjectType): token_auth = graphql_jwt.ObtainJSONWebToken.Field() verify_token = graphql_jwt.Verify.Field() refresh_token = graphql_jwt.Refresh.Field() schema = graphene.Schema(mutation=Mutation) However if I run the tokenAuth mutation it throws me the below error in the GraphiQL interface. Note that if I enter incorrect credentials it throws an "Please enter valid credentials" instead of the below. { "errors": [ { "message": "'str' object has no attribute 'decode'", "locations": [ { "line": 2, "column": 3 } ], "path": [ "tokenAuth" ] } ], "data": { "tokenAuth": null } } -
Django filter JSON field array for multiple indexes lookup with Q model?
Im using Django with Postgres and im having some trouble regarding filtering data into JSON field. --Here is my json object "dimensions": [ { "dimension": "140/200", "price": 163.52 }, { "dimension": "160/230", "price": 214.91 }, { "dimension": "200/290", "price": 338.72 } OR "dimensions": [ { "dimension": "160/230", "price": 214.91 }, { "dimension": "80/150", "price": 70.08 }, { "dimension": "140/200", "price": 163.52 }, { "dimension": "80/200", "price": 93.44 } --Here are my views and what i have tried: if min_price and max_price: queryset = queryset.filter( Q(product_options__options__data__dimensions__price = float(min_price), product_options__options__data__dimensions__contains=[{'price': float(min_price)}]) & Q(product_options__options__data__dimensions__price = float(min_price), product_options__options__data__dimensions__contains=[{'price': float(min_price)}])) -And finally im able to filter them using range filter queryset = queryset.filter(Q(product_options__options__data__dimensions__1__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)| Q(product_options__options__data__dimensions__2__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)| Q(product_options__options__data__dimensions__3__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)| Q(product_options__options__data__dimensions__4__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)| Q(product_options__options__data__dimensions__5__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId)) But here is my question is there any possibility to make this a single query because im hitting db multiple times with all indexes from 0 to n. I have tried with gte and lte but same. I need something like queryset = queryset.filter(Q(product_options__options__data__dimensions__{'Here to filter all indexes'}__price__range=[float(min_price),float(max_price)],sub_categories_id = subCategoryId) -
When testing login functionality I get ValueError
I am writing a test to check if a user can login without entering his username. However, when I run the test I get response: ValueError:The view posts.views.LoginPageView didn't return an HttpResponse object. It returned None instead. How can I fix it? This is my views.py class LoginPageView(View): def get(self, request): if request.user.is_authenticated: return redirect('/') form = LoginForm() return render(request, 'login.html', {'form': form}) def post(self, request): form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: # if user exists, login() function will keep him logged during session login(request, user) return redirect('/') else: return redirect('/login') This is my LoginPageViewTest(TestCase): def setUp(self): self.login_url=reverse('login') self.register_url=reverse('register') self.user={ 'username':'username', 'password':'password', 're_password':'password', 'first_name':'first_name', 'last_name':'last_name', 'email':'email@gmail.com' } def test_cant_login_with_no_username(self): response = self.client.post(self.login_url,{'username':'','password':'password'},format='text/html') self.assertEqual(response.status_code,401) -
django-dynamic-scraper-unable-to-scrape-the-data
I try this open source example and I found this here Django-dynamic-scraper unable to scrape the data, but there is not the same error. I get all data from github and load all example data, then I want to crawl with 2021-01-13 14:58:15 [scrapy.utils.log] INFO: Scrapy 2.4.1 started (bot: open_news) 2021-01-13 14:58:15 [scrapy.utils.log] INFO: Versions: lxml 4.6.2.0, libxml2 2.9.5, cssselect 1.1.0, parsel 1.6.0, w3lib 1.22.0, Twisted 20.3.0, Python 3.7.7 (tags/v3.7.7:d7c567b08f, Mar 10 2020, 10:41:24) [MSC v.1900 64 bit (AMD64)], pyOpenSSL 19.1.0 (OpenSSL 1.1.1i 8 Dec 2020), cryptography 3.3.1, Platform Windows-10-10.0.17134-SP0 2021-01-13 14:58:15 [scrapy.utils.log] DEBUG: Using reactor: twisted.internet.selectreactor.SelectReactor 2021-01-13 14:58:15 [scrapy.crawler] INFO: Overridden settings: {'BOT_NAME': 'open_news', 'SPIDER_MODULES': ['scrapy_django_dashboard.spiders', 'open_news.scraper'], 'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' '(KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'} 2021-01-13 14:58:15 [scrapy.extensions.telnet] INFO: Telnet Password: 00931b453fcba465 2021-01-13 14:58:15 [scrapy.middleware] INFO: Enabled extensions: ['scrapy.extensions.corestats.CoreStats', 'scrapy.extensions.telnet.TelnetConsole', 'scrapy.extensions.logstats.LogStats'] 2021-01-13 14:58:15 [asyncio] DEBUG: Using selector: SelectSelector 2021-01-13 14:58:15 [article_spider] INFO: Django settings used: example_project.settings 2021-01-13 14:58:15 [article_spider] INFO: Use ALL images store format (Scrapy behaviour, save both original and thumbnail images) 2021-01-13 14:58:15 [article_spider] INFO: Runtime config: do_action True 2021-01-13 14:58:15 [article_spider] DEBUG: Configuration set: {'DO_ACTION': True, 'RUN_TYPE': 'SHELL', 'SPLASH_ARGS': {'wait': 0.5}, 'IMAGES_STORE_FORMAT': 'ALL', 'CUSTOM_PROCESSORS': [] , 'LOG_ENABLED': True, 'LOG_LEVEL': 'ERROR', … -
How can i upload my Django project on Hostinger VPN?
How can i upload my project files and setup environment to execute python project at server (hostinger VPN server)? Is there any tutorial avaialble? My project is done in Django Framework and has mySQL database connection. Under VPN i have already created on folder and installed Python and Django. Regards, PD -
Custom SetPasswordForm not changing password on submit
I'm making a website and one of the features is that when user forgets his password he can reset it. We all know that templates provided by django aren't beautiful so I created my own. and everything works but the password_reset_confirm Just to be clear if i have my custom templates on every view (reset_password, password_reset_done and password_reset_complete) but I'm using django provided password_reset_confirm page works password is changed but when im using my template and form for this password stays the same Thanks for your help and have a great day btw if some code in views is requied im working with function based views Forms.py from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm class CustomPasswordResetForm(PasswordResetForm): email = forms.EmailField(widget=forms.TextInput(attrs={'class':'registerForm','name':'email'})) class NewPasswordResetForm(SetPasswordForm): error_messages = { 'password_mismatch': ('New Passwords and Confirm Passwords not matching'), } password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'registerForm','name':'new_password1','id':'id_new_password1'})) password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'registerForm','name':'new_password2','id':'id_new_password2'}) Urls.py from .forms import CustomPasswordResetForm, NewPasswordResetForm path('reset_password/', reset.PasswordResetView.as_view(template_name="resetPassword.html",form_class=CustomPasswordResetForm), name="reset_password"), path('new_password_send/', reset.PasswordResetDoneView.as_view(template_name="resetPasswordDone.html",), name="password_reset_done"), path('reset/<uidb64>/<token>/', reset.PasswordResetConfirmView.as_view(template_name="resetPasswordNew.html", form_class=NewPasswordResetForm), name="password_reset_confirm"), path('reset_password_complete/', reset.PasswordResetCompleteView.as_view(template_name="resetPasswordComplete.html"), name="password_reset_complete"), HTML <form method="POST" action=""> {% csrf_token %} <div class="form-group"> {{ form.password1 }} </div> <div class="form-group"> {{ form.password2 }} </div> <button type="submit" class="btnSbtRegister"> <span class="textSbtRegister"> {% trans "Change Pass" %} </span> </button> </form> -
Django error - 'function' object has no attribute [closed]
I have following problem: I would like to call a function vyroci_mesicV from a module vyroci in my view.py. When I simply try print(vyroci.vyroci_mesicV()) in the terminal in VS Code I got the desired output. However, when I run py manage.py runserverand run the local host I got and error message AttributeError: 'function' object has no attribute 'vyroci_mesicV' Here is the code of views.py if needed: def vyroci(request): error_msg = None vysledek = None if request.method == "POST": if (request.POST["operator"] == "Vysehrad"): vysledek = vyroci.vyroci_mesicV() else: error_msg = "something wrong :(" return render(request, "vyroci/vyroci.html", dict(error_msg=error_msg, vysledek=vysledek)) return render(request, "vyroci/vyroci.html", dict(error_msg=error_msg, vysledek=vysledek)) and here the vyroci.html if neede: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>XXX</title> </head> <body> <form method="POST"> {% csrf_token %} <span style="color: red;">{{error_msg}}</span> <br> <select name="operator"> <option value="Vysehrad" {% if request.POST.operator == "Vysehrad" %} selected {% endif %}>Vyšehrad</option> </select> <input type="submit"><br> {{vysledek}} </form> </body> </html> -
In HTML unable to execute django if statement
enter image description here I have created models as shown in the picture. In the index page to display certain content, the member must be active. I am trying to use the if statement. {% if user.active == True %} do this... {% endif %} The above code is not working, also django is not throwing any error. Can anyone please help me on this? -
How can i include a searchbox in a Django FilteredSejectMultiple Widget
I'm a little bit new to django, i've done a couple of practice projects before but this is the first serious one. I'm trying to make a recipe webpage where users can upload, share and search cooking recipes. When writing a new recipe, i want users to be able to attach some already written recipe (lets say they are writing a goulash recipe, i want them to be able to say "here is an old spätzle recipe i really like"). So, in the RecipeModel this is a ManyToMany field and works just fine, but in the RecipeForm i'm really struggling: there would be too many recipes in the database to just list them all up in a dropbox, there should be a searchbox where Users can type the name of the one or multiple recipes they want to link. I know there's this "FilteredSelectMultiple" Widget that should do the work, but I just couldn't find any explanation of how to include a searchbox on it. -
Proper way to backup and restore django project
I have been using Oracle's virtual box to setup an Ubuntu 18.04LTS OS to run my django application. The application is using MySQL as a database. The problem happened a few days ago, all my files suddenly became read-only, which is an indication of hard disk problems as seen in this post. I have since prepared another server to run the application, however I would like to know the proper procedures in migrating data to ensure that I don't loose any of my files. Could someone point me in the correct direction? Thank you. -
How to redirect to the same page location after submitting a form in django?
In a blog post comment, I want to redirect to the comment location after submitting new comment. How am I suppose to do it? Thanks in advance. -
Customise choices for BooleanWidget in django_filters
I'm using django_filters. For boolean fields, it generates this HTML: <select name="bass" id="id_bass"> <option value="">Unknown</option> <option value="true" selected="">Yes</option> <option value="false">No</option> </select> This springs from Django's own specifics of NullFields. How can I change that ugly 'Unknown' to something else? the user is not really searching for 'Unknown'; they're searching for 'all', since my boolean field is required and either true or false. The widget does not accept a choices attribute. Creating manually the HTML myself partially solved the issue; nevertheless, I would achieve this from the view and use only the {{form}} on the template. -
Error after overriding create method in serializer
I'm Overriding create method of serializer in order to manipulate validated_data and create object in a model, Although it works, in the end I get below error, i am not able to figure out why after lot of research. AttributeError: Got AttributeError when attempting to get a value for field `shift_time` on serializer `PunchRawDataAndroidSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `PunchRawData` instance. Original exception text was: 'PunchRawData' object has no attribute 'shift_time'. class PunchRawDataAndroidSerializer(serializers.ModelSerializer): employee_id = serializers.CharField() shift_id = serializers.CharField() work_location_id = serializers.CharField() shift_time = serializers.TimeField() class Meta: model = PunchRawData fields = ['employee_id', 'shift_id','work_location_id', 'punch_type', 'actual_clock_datetime', 'emp_photo', 'created_at', 'updated_at','shift_time'] def create(self, validated_data): validated_data.pop('shift_time') request_data = self.context.get('request') user = request_data.user validated_data['user'] = user data = validated_data return PunchRawData.objects.create(**data) class PunchRawDataAndroidViewSet(viewsets.ModelViewSet): serializer_class = PunchRawDataAndroidSerializer parser_classes = (MultiPartParser, FileUploadParser) -
requests Python lib saves wrong cookie value, invalid JSON str
I am using "requests" latest version in Python. I am sending get/post requests via request.Session(), so the session created is holding the cookies values set by the server. Say my server sets cookie when i GET request some url, the cookie is set in JSON str format. s = requests.Session() s.get("https://www.example.org/api/bla) # Cookie is set print(s.cookies["my_cookie"]) When i check the value of the cookie planted (s.cookies["my_cookie"]) the JSON str format is wrong, it looks like this: '"{key1: value1\\054 key2: value2\\054 key3: value3\\054 key4: value4\\054 key5: value5}"' When i repeat the same request on Chrome browser client, the cookie looks OK. "{\"key1\": \"value1\"\054 \"key2\": \"value2\"\054 \"key3\": \"value3\"\054 \"key4\": \"value4\"\054 \"key5\": \"value5\"}" What can cause this? i don't think it's an issue is on "requests" lib side. I also know that the client sending back the cookie in wrong format, because when the cookie value is valid, the server creates a db object, but via my client (requests lib) the object is not created. Stuff i tried with no help: Changing my custom headers to the same as chrome Updating/Downgrading requests lib Thanks in advance.