Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Microsoft.Web/sites/extensions cannot be exported yet and is not included in the template
{"code":"ExportTemplateCompletedWithErrors","message":"Export template operation completed with errors. Some resources were not exported. Please see details for more information.","details":[{"code":"ExportTemplateProviderError","target":"Microsoft.Web/sites/extensions","message":"Could not get resources of the type 'Microsoft.Web/sites/extensions'. Resources of this type will not be exported."}]} -
Not show ids in django response
Good day guys, I'm using rest-freamework to create some APIs, in the response I don't want to show ids in the foreign fields. { "id": 1, "name": "My Team", "description": "This is my team", "dealership": 1, "users": [ 6, 9, ] } In change I want something like: { "id": 1, "name": "My Team", "description": "This is my team", "dealership": "Chevrolet Miami", "users": [ "Jack Black", "Brad Pitt" ] } -
permalink error when calling get_absolute_url
def get_absolute_url(self): return ('threads_reply', [self.id]) get_absolute_url = models.permalink(get_absolute_url) I am migrating app from django 1.8 to django 2.2 and python 2.7 to python 3.6 I am getting error at that function, how can I change it correctly? I tried multiple ways it didnt work. -
Form customization in Django template
I want to add styling to the below form (main objective is to change the text color of placeholder as my form is of dark color and the placeholder is not visible due to its default gray color) I am sure there must be some way to achieve this in the template only. ::placeholder { color: aquamarine; opacity: 1; } <form action="{% url 'register' %}" class="box" method="POST"> <input type="text" name="username" placeholder="{{form.username.label}}" id=""/> <input type="text" name="firstname" placeholder="{{form.first_name.label}}" id="" /> <input type="text" name="lastname" placeholder="{{form.last_name.label}}" id=""/> <input type="text" name="email"placeholder="{{form.email.label}}"id="" /> <input type="text" name="password1" placeholder="{{form.password1.label}}" id=""/> <input type="text" name="password2" placeholder="{{form.password2.label}}" id=""/> <input type="submit" value="Submit" /> </form> This is my form that I have created to add a new user (django.contrib.auth.models User). I am not sure how do I use {{form.username}} in the existing form. If I simply put {{form.username}} to the form it is creating a new field without any styling applied to it. -
Django form request.POST is not valid in views.py
I have a problem and been not able to solve it. I have something like a decision tree. First in GET some questions are asked with a static form. Then in the first request.POST (CalculationForm) the user gets an answer. But the user can choose an Alternative, so it is generated a second form depending on the input in the first form. But the AlternativForm is not valid. I hope it is clear what I try to say: The first Django form is fine and the form(request.POST) generates the second form (AlternativForm). But the second form is not valid and I can’t find the mistake. views.py def calc(request): if request.method =="POST": #asking reuqest.POST if it is the first form, here everything is fine #I have shortened this part 'cause I'm sure that it is not relevant if request.POST.getlist('km'): try: get_form = CalculationForm(request.POST) if get_form.is_valid(): op, ab, km, tro = get_form.cleaned_data['op'], get_form.cleaned_data['ab'], get_form.cleaned_data['km'], get_form.cleaned_data['tro'] response = program_handle_nodry.handle(request, op, ab, tro, km) return response except: pass #The relevant part, checking if it is the second form; this one is not valid and I don't know why if request.POST.getlist('konserv'): get_form1 = AlternativForm(request.POST) #print the exact fields of AlternativForm print(get_form1.visible_fields) #print nothing, no error … -
Django - intercepting a model change with the pre_save() hook
I was wondering, I have the following pre_save() signal intercept: def model_pre_save(sender, instance, *args, **kwargs): if instance.uuid: my_model = Model.objects.get(uuid=instance.uuid) if my_model.has_signed_exception: # Once signed, no one can overwrite this value: instance.has_signed_exception = True pre_save.connect(model_pre_save, sender=Model) I was wondering - the instanced that is sent seems to be the instance that is being updated - but is there an argument I can use to get the exisiting instance, rather than making a further DB call on every save? -
How to fix Page Not Found (404) error in django
How to fix this error in django 3.0, when im trying to reach a page using form post method, I getting this error Hi, Im new to Django programming language, Now im developing a college project in django, When Im using forms to create login in POST method. If I put it on main page, It's working well. But when I put the forms into inside of another page (about.html) I got this error. I can't fix it. So guys Please help me.. > Page not found (404) Request Method: POST Request > URL: http://127.0.0.1:8000/about/login Using the URLconf defined in > mysite.urls, Django tried these URL patterns, in this order: > > [name='home'] login/ about/ admin/ The current path, about/login, > didn't match any of these. > > You're seeing this error because you have DEBUG = True in your Django > settings file. Change that to False, and Django will display a > standard 404 page. app/ Urls.py from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home'), path('', views.about, name="about"), path('', views.login, name="login") path('admin/', admin.site.urls), ] project/ urls.py from django.contrib import admin from django.urls import path,include from pages.views import home, about, login urlpatterns = [ path('',home,name='home'), … -
Why does delete_file raise an error when running collectstatic with Django 3.0.2?
An error occurs when running collectstatic in Django 3.0.2. I'm uploading the files to Google Cloud Storage with the following settings: STATIC_ROOT = os.path.join(BASE_DIR, 'myapp/static') STATIC_URL = 'https://storage.googleapis.com/[*** bucket ***]/static/' STATICFILES_STORAGE = 'myapp.storage.MyCustomStorage' # Without the below, the files get uploaded to root STATICFILES_DIRS = [ ('static', 'myapp/static') ] All of the files upload fine, but afterwards I get the following error: File "django/contrib/staticfiles/management/commands/collectstatic.py", line 271, in delete_file can_skip_unmodified_files = not (self.symlink ^ os.path.islink(full_path)) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/posixpath.py", line 169, in islink st = os.lstat(path) TypeError: lstat: path should be string, bytes or os.PathLike, not NoneType It's something to do with removing files, but I'm not really sure where to start digging. -
Nesting Django block with {% include %}
I am trying to nest blocks with Django 3. I have sections of html that are sometimes reused on a page. I don't think I would have to resort to duplicating templates, but I can't get it to work; I have this template {% extends 'base.html' %} {% include 'site_part.html' %} {% block content %} Some Content <br> And here I insert the child content {% block part_of_site %} {% endblock %} {% endblock %} And the site_part_html is like this; {% block part_of_site %} Okay, i am loaded! {% endblock %} In the base.html I have only this: {% block content %} {% endblock %} I'd expect it to render the "Okay, i am loaded!" string in the resulting page, in the content block. However, it remains empty. I've looked, but most examples are far more advanced then what I need and I can't get those to work either. If I remove the extends statement at that start and the block content lines, it does load the included html. Basically, I have a site part that sometimes is need, and I'd like to included that based on some templating. Otherwise, I'd have duplicate that code for each of the … -
Django Management command for Activating/Deactivating admin site
I would like to know if it's possible to 'Activate' and 'Deactivate' the admin site using a custom management command and what i mean by deactivating is commenting the line containing the path of admin.site.urls in the main urls.py file. Or if there is a better way to do this. -
Django: How to lock a Boolean field for futher updates once set to True?
I'm wondering, I am managing a transition between two systems - and in one system I am using Django as the ORM and API backend. I have a field that I want to set to True, and once it is set to True, it stays True. Even if the update from the older legacy system wants it to be False. Is there a Django way to do this? Maybe overriding the save() method? -
How do i alias a composite value of 2 fields inside the values_list method of object_manager?
I am trying to create a really simple form that allows the user to select an active user from a selection list and submitting that choice to the backend. Here is my code: class PeerReviewColleagueSelectionForm(forms.Form): ACTIVE_COLLEAGUES = CustomUser.objects.filter(is_active=True)\ .values_list('id', full_name=F(('first_name') + ' ' + F('last_name')))\ .order_by('full_name').annotate(Count='id') colleague = forms.ChoiceField(label='selecteer collega', tuple=ACTIVE_COLLEAGUES) I am trying to get a list of tuples that can be used by the ChoiceField widget to display all the available active colleagues to choose from. I'm trying to create an alias called full_name from the first_name and last_name fields of CustomUser. Then I want to order the results by that alias and i use annotate(count) to group by id (since i know each id is unique and i want tuples consisting of (id, full_name,) However when i try this it throws: TypeError: values_list() got an unexpected keyword argument 'full_name' How can i make a tuple based on the id and an alias called full_name? -
Forbidding more than 1 instance of a Model saved to DB (Django)?
I have a django model and I would like to limit the amount of instances it has in the DB to 1. However, I would like to allow that 1 instance to be edited and updated. I tried using a @receiver signal to count the number of instances before allowing to save, but if I limit it that way, it would not let the admin edit the instance either. Is there a way to differentiate between a create vs. an edit action in the signal sender? @receiver(pre_save, sender=myModel) def checkLimit(sender, **kwargs): count = sender.objects.count() if count > 1: raise PermissionDenied -
Everytime i login with new user , it returns the previous user cart items in django
def _cart_id(request): cart=request.session.session_key if not cart: cart=request.session.create() return cart def add_cart(request, product_id): product=Product.objects.get(id=product_id) try: cart=Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart=Cart.objects.create(cart_id=_cart_id(request)) cart.save() try: cart_item=CartItem.objects.get(product=product,cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item=CartItem.objects.create( product=product, quantity=1, cart=cart ) cart_item.save() return redirect('cart_app:cart_detail')*emphasized text* -
Django url || 502 Bad Gateway
I have just deployed mt Django project into server and when one of the url is hit, it is showing as "502 Bad Gateway || nginx/1.10.3 (Ubuntu)" and in the log, it is not even showing that this url has been hit. To my surprise, the same url is opening and working fine in my localhost. Please suggest how to fix this? -
Django PyJwt: How to logout a user for a particular login by changing the secret key
In Django i am developing an api for user login and logout. I am using Jwt token based authentication. I have 30days expiration for the token jwt.encode( payload = { user_id='2', exp= datetime.datetime.utcnow() + datetime.timedelta(days=30)}, key, algorithm ) My user can login on two different browsers. When he logs out from a browser the token is still valid till it gets expired. So the suggested solution is that: On your user model add a field: jwt_secret = models.UUIDField(default=uuid.uuid4 And when one logouts change the secret key of the user Logout_view(request) request.user.jwt_secret = uuid.uuid4() request.user.save() But this will logout from all the browsers How to have a secret_key stored per login instance and invalidate it. And when i want to logout user from all logins i change the SECRET_KEY of the user So the key passed in the jwt.encode should be something like key = function (USER_SECRET_KEY & key based on login instance of that user) How to do this in django -
InMemoryUploadedFile to binary string in Django
I need to send file as BinaryData string to some API. Example files = request.FILES for file in files.values(): requests.post( url='some_url', headers={ "Content-Type": "application/json", "Authorization": "Bearer {}".format(token) }, json={ "inputs": [ { "type": "identity_assurance.document_verification.americas.us.drivers_license.image.back", "value": { "$objectType": "BinaryData", "data": file.read(), "metadata": { "cropped": False }, "mime_type": "image/png" } }, ] } ) But I got TypeError: Object of type bytes is not JSON serializable on file.read(). In data field should be byte string -
Django - Overwrite existing data in database
I have a model that looks like this: class ModelA(models.Model): name = models.CharField(max_length=200) forms that looks like this: class NameUpdateForm(forms.Form): name = forms.CharField(label='name') <form method="POST" id="name_update_form" autocomplete="off"> {% csrf_token %} {% for field in form.visible_fields %} <div class="form-group inlinethis"> {{ field.label_tag }} {{ field }} </div> {% endfor %} <button type="submit" class="btn btn-primary-submit">Submit</button> </form> and a view that looks like this: def update_name(request, NameUpdateForm): if request.method == "POST": form = NameUpdateForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Added Successfully!') return redirect('index') else: form = NameUpdateForm() return render(request, 'header.html', {'form' : form}) Question: How do I overwrite the existing data in the database, rather than having a new db entry each time the users submits the form? I would appreciate a link to the documentation where I can read more about this and a working example. Thank you very much -
Django making instance of class in two different views does not function
Im trying to create an instance of a class i made called Alert, so i can show alerts in my template by looping through each instance i created. So i have a simple Alert class like this: Alert Class: class Alert(): def __init__(self,level, content): self.level = level self.content = content I have a model of Employees to show some data about them. Model Employee: class Employee(models.Model): owner = models.ForeignKey(User,to_field = 'username', on_delete = models.CASCADE,null = True) name = models.CharField(max_length= 255) class Meta: ordering = ['-id'] unique_together = ['name','owner'] def __str__(self): return self.name I have two views like the following: View Add Employee: @login_required(redirect_field_name = '/login',login_url='/login') def add_employee(request): if request.method == "POST": try: name = request.POST['name'] query = Employee(name = name,owner = request.user) query.save() return redirect("main:somepage") except: instance = Alert(level = 'error',content = 'This username is already exist in your employee list!') return redirect("main:somepage") And this is my second View: View Delete Employee: @login_required(redirect_field_name = '/login',login_url='/login') def delete_employee(request): if request.method == "POST": query = Employee.objects.filter(owner = request.user,name = request.POST['name']) if len(query) == 1: query.delete() instance2 = Alert(level='success', content='Successfully Deleted!') return redirect("main:main_manage") Now those views are being called once in my template user requests to add or to delete obviously. Above Those … -
Forbidden (CSRF cookie not set.): /test/googleUser/ on ajax requests
So I was trying to setup user login using google api and sending some data to the backend using ajax post method to backend to store profile data in database. The problem I am running into is I'm unable to post data to the backend. I read the documentation and few questions related to the issue and updated code to include csrf_token but it keeps bugging me with 403 error, even after including the csrf header below is the all relevant code that I'm using. Is there a better way of doing this? If yes please explain since I'm a beginner and don't really know much about these things. Any help will be appreciated. :) <script src="https://apis.google.com/js/platform.js" async defer></script> <script type="text/javascript">CSRF_TOKEN = "{{ csrf_token }}"; </script> <meta name="google-signin-client_id" content="875378837481-indv7hibsjeubu1h6mnl0e0a2eukmp19.apps.googleusercontent.com"> <div class="g-signin2" data-onsuccess="onSignIn"></div> and onSignIn is as follows function onSignIn(googleUser) { var id_token = googleUser.getAuthResponse().id_token; $.ajax({ headers: { "X-CSRFToken": CSRF_TOKEN }, type: "POST", url: "/test/googleUser/", data: { token: id_token, }, }); } -
Django exclude path from if statement while true
my website has a maintenance mode and the default django login page has been overwritten by my own login. Now im facing the problem as soon as the maintence mode is enabled im not able to display the login CAPTCHA anymore as it's also getting filtered by my middleware. So the question is how can i make the path to my CAPTCHA at login still reachable while the application is in maintenace mode? middleware.py class MAINTENANCE: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if config.MAINTENANCE_ENABLED == True and config.ADMIN_INTERFACE_LINK not in request.path and not (request.user and request.user.is_superuser): return render(request, 'app/maintenance.html', {'config': config}, status=503) else: return response the path where my captcha gets loaded from is: http://localhost/captcha/image/fd340080666b9958/ while "fd340080666b9958" is always a random value on each page reload. Thanks in advance -
How to get file name in UpdateView (Create View) in Django
i got a simple model models.py class Inform_note(models.Model): id = models.AutoField(primary_key=True) in_note_on = models.FileField(upload_to='notes', blank=True) note_date = models.DateField(auto_now_add=False, blank=True, null=True) With CreateView i can create a new records, edit this records with my UpdateView, add files etc... view.py class Inform_noteEditView(generic.UpdateView): model = Inform_note fields = '__all__' def get_form(self, form_class=None): form = super().get_form(form_class) form.helper = FormHelper() form.helper.add_input(Submit('submit', 'Create', css_class='btn-primary')) form.fields['in_note_on'].label = "Выписка об ОН" return form But before 'return form' i want to see a filename in field (in_note_on). print(form.fields['in_note_on']) returns <django.forms.fields.FileField object at 0x00000000062D9710> Any ideas how to get file name in this field ? -
Ajax async: false not working with jQuert Selectors
I am working on a front-end application using Django. I encountered something strange. I have to carry out a basic task, get data from an endpoint and place it in an HTML table. The initial code, which is working, is similar to the one below: $.ajax({ url : data_url, type : 'GET', dataType : 'json', beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", token) }, success : function(data) { console.log(data); $('#data_table').bootstrapTable('load',data); } }); The data gets successfully retrieved, logged in the console and displayed in the table. The moment I add async: false to the ajax call, the data is retrieved, logged but NOT displayed in the table anymore. Why does this happen? Shouldn't the async: false just specify to the js engine that this code will not run asynchronously and all the subsequent calls will have to wait after the current service to complete its execution? Why does this affect the display of the data, inside the table? Thank you! -
Django Admin SerializationError: TypeError("Unable to serialize <User: admin>
I am a newbie to Django. I am trying to add a Report instance from the admin panel. I am getting a SerializationError when I try to save the form. I defined in the Report Model in models.py a ForeignKey id_owner related to User from django.contrib.auth.models. In the admin.py I override the save method to save the user object like this: class ReportAdmin(admin.ModelAdmin): list_display = ('nm_report', 'id_object', 'id_perspective', 'ds_report', 'nm_department', 'id_owner', 'dh_update_date', 'fl_natural_language') list_filter = ('nm_report', 'id_object', 'id_perspective', 'ds_report', 'nm_department', 'id_owner', 'dh_update_date', 'fl_natural_language') ordering = ('nm_report', 'id_object', 'id_perspective', 'ds_report', 'nm_department', 'id_owner', 'dh_update_date', 'fl_natural_language') search_fields = ('nm_name', 'id_object', 'id_created_by__name', ) exclude = ('dh_created', 'id_created_by', 'dh_last_modified', 'id_last_modified_by', ) def save_model(self, request, obj, form, change): obj.id_owner = request.user super().save_model(request, obj, form, change) admin.site.register(dictionary_models.Report, ReportAdmin) The error I get: SerializationError at /admin/dictionary/report/29/change/ ({'id': 29, 'nm_report': 'Report', 'ds_report': 'description', 'id_created_by': {}, 'id_last_modified_by': {}, 'id_owner': User: admin, 'id_perspective': {'id': 1, 'nm_perspective': 'Perspectiva1'}, 'dh_created': datetime.datetime(2020, 1, 28, 16, 16, 1, 82882, tzinfo=UTC), 'nm_department': 'departamento', 'id_dossier': 'id del dossier', 'fl_oficial_field': True, 'nm_oficial_text': '.', 'fl_natural_language': False, 'nu_sensitivity': 2, 'fl_show_private': True, 'dh_update_date': datetime.datetime(2020, 1, 28, 16, 15, 41, tzinfo=UTC)}, TypeError("Unable to serialize (type: class 'django.contrib.auth.models.User')")) The Report model in models.py: class Report(models.Model): nm_report = models.CharField(max_length = 255, verbose_name="Nombre") id_object = … -
Django Production Error : ProgrammingError at /admin/posts/post/add/
django production error (Heroku) : column "author_id" of relation "posts_post" does not exist LINE 1: INSERT INTO "posts_post" ("author_id", "title", "content", "... everything is perfectly fine while running it in localhost but where as when i deployed it into herouko and tried to add a post i'm facing this issue i tried all possible ways removed database , applied migrations applied fake migrations but every thing is of no use here is the complete traceback: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) The above exception (column "author_id" of relation "posts_post" does not exist LINE 1: INSERT INTO "posts_post" ("author_id", "title", "content", "... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/admin/options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 231, in inner return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/admin/options.py", line 1638, in add_view return self.changeform_view(request, None, form_url, …