Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'AnonymousUser' object has no attribute '_meta' error in Django Register function
I was trying to do Register and Login form but I am taking "'AnonymousUser' object has no attribute '_meta'" error I hope somebody can help me. And also if you have suggestion for better code writing or better way for this form I would be happy. Here is my views.py from django.shortcuts import render,redirect from .forms import RegisterationForm from django.contrib import messages from django.contrib.auth import login as dj_login from django.contrib.auth import authenticate from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import logout as dj_logout def register(request): if request.method == "POST": form = RegisterationForm(request.POST) if form.is_valid(): user = { "username" : form.cleaned_data["username"], "email" : form.cleaned_data["email"], "password1" : form.cleaned_data["password1"], "password2" : form.cleaned_data["password2"] } user = form.save() dj_login(request,user) messages.success(request,"Kayıt İşleminiz Başarıyla Gerçekleştirilmiştir.") return redirect("index") else: messages.error(request,"Kayıt İşlemi Sırasında Bir Hata Meydana Geldi.") return render(request,"register.html",context={"RegisterForm":form}) else: form = RegisterationForm() return render(request,"register.html",context={"RegisterForm":form}) And here is my register.html file. {% extends 'layout.html' %} {% load crispy_forms_tags %} {% block title %} Register {% endblock title %} {% block body %} <h1>Register</h1> <form method="post"> {% csrf_token %} {{RegisterForm.username.label}} {{RegisterForm.username}} <br><br> {{RegisterForm.email.label}} {{RegisterForm.email}} <br><br> {{RegisterForm.password1.label}} {{RegisterForm.password1}} <br><br> {{RegisterForm.password2.label}} {{RegisterForm.password2}} <br><br> <button type="submit">Kayıt Ol</button> </form> {% endblock body %} -
Conditional Boolean Attribute in Django
I want to have a BooleanField private in my models for my project, but I only want to show this, if another field has a particular value. This is my Model: class Scope(models.TextChoices): COMPANY = 'company', _("Company") TEAM = 'team', _("Team") INDIVIDUAL = 'individual', _("Individual") class Objective(models.Model): name = models.CharField(max_length=500, verbose_name=_("name")) scope = models.TextField(_("Scope"), max_length=15, choices=Scope.choices, db_index=True, default=Scope.TEAM) is_private = models.BooleanField(default=False, verbose_name=_("private")) def __str__(self): return self.name Now I only want to show the is_private BooleanField in the Form, when the Scope of the Objective is INDIVIDUAL. How can I do this? -
Handle revoke command from inside task
Is there a way to handle revoke commands inside the task logic? Since I'm doing some computations and database manipulation on RUNNING tasks I'd like to handle a revoke user request using the data of the task itself. I've already tried capturing the celery.exceptions.Terminated or celery.exceptions.WorkerTerminated exceptions but it doesn't seem to work as expected. from celery import shared_task, exceptions @shared_task( name="tasks.trigger_sales", bind=True ) def trigger_sales_job(self): try: logger.info('Executing task id {0.id}, args: {0.args!r} kwargs: {0.kwargs!r}'.format(self.request)) # Do some work on DB return True except (exceptions.Terminated, exceptions.WorkerTerminated) as e: logger.warning(f"Task {self.request.id} has been terminated by user request.") -
Convert model objects in OrderedDict to Json django
In [32]: obj OrderedDict([('code', 'COO21'), ('name', 'sai'), ('country', <Country: INDIA>)]) Error:- TypeError: Object of type Country is not JSON serializable Not able to convert model objects in ordered dict to json -
Django Channels tests: Task x got Future y attached to a different event loop
Whilst trying to test a websocket consumer, I get this error: Error Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/asgiref/testing.py", line 74, in receive_output return await self.output_queue.get() File "/usr/local/lib/python3.10/asyncio/queues.py", line 159, in get await getter asyncio.exceptions.CancelledError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/asgiref/testing.py", line 73, in receive_output async with async_timeout(timeout): File "/usr/local/lib/python3.10/site-packages/asgiref/timeout.py", line 65, in __aexit__ self._do_exit(exc_type) File "/usr/local/lib/python3.10/site-packages/asgiref/timeout.py", line 102, in _do_exit raise asyncio.TimeoutError asyncio.exceptions.TimeoutError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/asgiref/sync.py", line 218, in __call__ return call_result.result() File "/usr/local/lib/python3.10/concurrent/futures/_base.py", line 439, in result return self.__get_result() File "/usr/local/lib/python3.10/concurrent/futures/_base.py", line 391, in __get_result raise self._exception File "/usr/local/lib/python3.10/site-packages/asgiref/sync.py", line 284, in main_wrap result = await self.awaitable(*args, **kwargs) File "/opt/project/backend/src/sergei/websocket/tests.py", line 57, in test_connection_with_login connected, _ = await self.communicator.connect() File "/usr/local/lib/python3.10/site-packages/channels/testing/websocket.py", line 36, in connect response = await self.receive_output(timeout) File "/usr/local/lib/python3.10/site-packages/asgiref/testing.py", line 82, in receive_output await self.future RuntimeError: Task <Task pending name='Task-14' coro=<AsyncToSync.main_wrap() running at /usr/local/lib/python3.10/site-packages/asgiref/sync.py:284> cb=[_run_until_complete_cb() at /usr/local/lib/python3.10/asyncio/base_events.py:184]> got Future <Task cancelling name='Task-13' coro=<CoreWebsocketConsumer() running at /usr/local/lib/python3.10/site-packages/channels/consumer.py:92>> attached to a different loop With the following code: class CoreWebsocketTest(TransactionTestCase): def setUp(self): self.communicator = WebsocketCommunicator(CoreWebsocketConsumer.as_asgi(), WEBSOCKET_PATH) async def test_connection_with_login(self): connected, _ = await self.communicator.connect() assert connected … -
Improve performance of Graphql (graphene-django) for 4 levels of nested lists
I am using Django 4 with graphene-Django 3 and I need to structure a response that must be 4 levels of lists and the bottom level a dictionary. Here the implementation class FailureSensorType(DjangoObjectType): class Meta: model = FailureSensor spectra = graphene.Field(SpectraGraphType) ... rest of fields class SpectraGraphType(graphene.ObjectType): name = graphene.List(graphene.String) spectra_z = graphene.List(graphene.List(graphene.List(SpectraZGraphType))) class SpectraZGraphType(graphene.ObjectType): _id = graphene.String(required=False) collection_name = graphene.String(required=False) values = graphene.List(graphene.Float, required=False) values_names = graphene.List(graphene.Int, required=False) sidebands = graphene.List(graphene.Float, required=False) rpm_detected = graphene.Int(required=False) anomaly = graphene.Int() def resolve_spectra(self, info): if self.anomaly_type == "spectra": spectra_name = set() for graph_y in self.get_map_Y(): spectra_name.add(str(self.id) + '-' + graph_y.split()[-1]) spectra_z_list = list() spectra_z_list_new = list() for i, x in enumerate(np.split(self.get_map_Z(), id_z)): spectra_z_list.append(x.tolist()) for spectra_z in spectra_z_list: zero_index_list = list() for index_obj, graph_z_obj in enumerate(spectra_z): zero_index = list() for i, graph_z_value in enumerate(graph_z_obj): if graph_z_value != '{"anomaly": 0}': zero_index.append(i) zero_index_list.append(zero_index) new_z_list = list() for z_obj in spectra_z: new_z = [v for i, v in enumerate(z_obj) if i in zero_index_set] z_dict_list = list() for dict_string in new_z: r = json.loads(dict_string.replace("|", ",").replace("(", "[").replace(")", "]")) if "_id" not in r: r["_id"] = "" if "collection_name" not in r: r["collection_name"] = "" if "rpm_detected" not in r: r["rpm_detected"] = -1 if "values" in r: r["values"] = … -
Why does Django password reset email not sent to btopenworld?
I'm using the Django built in password reset functions and I'm having a weird thing happen. The emails seem to get sent for some people and not others. I tried the system for myself (I have two email addresses) and the Django password reset function works for one of my addresses and not for the other, i.e. I do not receive an automated email with a link to a password reset facility. I'm having problems with a '@btopenworld.com' address. Is this inconsistency a known problem in Django, or have I likely missed something? All my other email functions in the app work perfectly. Thanks -
is there a way to pass string id in django url?
Template.html for all model row This Template is a table to show all my model data when the user click one row tr tag its should direct them to the view of the row to edit or update. tr onclick="location.href='{% url 'quality_control_point_view' object.id %}'" When this object.id was int AutoField it worked just fine for me but when i modify my model so that the primary key is Charfield. an error keep coming <form action="" method="post"> {% csrf_token %} <table id="material_issued"> <tr > <th>{% translate 'Reference' %}</th> <th>{% translate 'Title' %}</th> <th>{% translate 'Product' %}</th> <th>{% translate 'Operation' %}</th> <th>{% translate 'Control Per' %}</th> <th>{% translate 'Type' %}</th> <th>{% translate 'Team' %}</th> </tr> {% for object in table %} <tr onclick="location.href='{% url 'quality_control_point_view' object.id %}'"> <td>{{ object.id }}</td> <td>{{ object.title }}</td> <td> {% if object.raw_product is not None %} {{ object.raw_product }} {% elif object.spare_product is not None%} {{ object.spare_product }} {% else %} {{ object.bom_product }} {% endif %} </td> <td >{{ object.operation.capitalize }}</td> <td>{{ object.control_per.capitalize }}</td> <td>{{ object.type.capitalize}}</td> <td>{{ object.team }}</td> </tr> {% endfor %} <input type="hidden" name="length" id="num" value="{{ table.count }}"> </table> </form> Urls.py for specific row path('Quality/QualityControlPoint/<str:qcp_id>', views.QualityControlPointView.as_view(), Urls.py for all model row path('Quality/QualityControlPoint', views.AllQualityControlPointView.as_view(),name='all_quality_control_point'), View.py … -
In Django how would you setup user permissions for a user to only have access to a rest api?
In our project users can generally login to the system and access vaious web-pages. There is also a rest-api - users can access certain information through rest api as well (token authentication). Now there is one user that only should have api-access - login only through an api call returning the token. Access to web-pages in not desired and should be prevented for this user. How can we set this up? Is it possible right out of the box or is it necessary to adapt permission classes? -
Swagger codegen with write_only PrimaryKeyRelatedField
In our project we have the following case more than once: class TestSerializer(serializers.ModelSerializer): unit = UnitSerializer(read_only=True) unit_id = serializers.PrimaryKeyRelatedField( queryset=Unit.objects.all(), source="unit", write_only=True) This is according to our best practices where variables should describe which type they contain. In drf-yasg this is shown however as required in both the Read and the Write way. This means that code generators will mark this field as required, and when our API response comes in, they invalidate the request, because the unit_id is missing. Is there a way to declare this field as write_only other than this parameter? -
Updating FileField in Django Form
Playing around with FileFiled and trying to update a form. I think my problem comes from the views.py. I have a template where I can see a product, and I have the option to update the product by clicking on the update button. When clicking on the update button, I am redirected to a form where I can update the product. template {% for TermsAndConditions in commercial_list %} <a class="btn btn-outline-secondary" href="{% url 'update-commercial' TermsAndConditions.id %}">Update </a> {% endfor %} My normal upload form (without FileField) looks like this: views (without FileField) def update_commercial(request, termsandconditions_id): commercials = TermsAndConditions.objects.get(pk=termsandconditions_id) form = TermsAndConditionsForm(request.POST or None, instance=commercials ) if form.is_valid(): form.save() return redirect('list-commercial') return render(request, 'main/update_commercial.html',{'form':form,'commercials':commercials}) With the addition of the FileField, I thought I would do something like this: views (with FileField) def update_commercial(request, termsandconditions_id): commercials = TermsAndConditions.objects.get(pk=termsandconditions_id) form = TermsAndConditionsForm(request.POST or None, request.FILES ,instance=commercials ) #the change being request.FILES if form.is_valid(): form.save() return redirect('list-commercial') return render(request, 'main/update_commercial.html',{'form':form,'commercials':commercials}) Problem is, when I do that the update button in the template becomes invalid (it doesn't redirect to the update form). I think my problem is how to handle the or None and request.FILES together. I tried different combinations but none have worked. Hoping … -
Django model forms validation in Django admin enters clean method when model validation has failed
I have a Django admin class defined like this: class MyModelAdmin(admin.ModelAdmin): form = MyForm class MyForm(forms.ModelForm): class Meta: model = Task fields = ('project', 'title', 'description', 'internal_assignees', 'task_list', 'additional_description', 'labels', 'skill_level', 'estimated_hours', 'merge_request_url', 'branch_name',) def clean(self): super().clean() print(self.errors) Assume my model has a required field, which the user does not submit when performing POST request. The expected behavior in this case is that Django will not enter my overriden clean method. But it actually does. And self.errors contain error message. The expected behavior was that Django will not enter the clean method if any of the required fields have not been submitted and will raise Bad request. Do I understand something incorrectly ? If so, does it mean that I have to check whether required fields are not or not in my clean method? -
Node.js vs something else?
i need develop a airport transfer service website. I just look up on internet and find a few course and all build by node.js on backend. i wonder should I build that website by using node.js or do you have any other suggestions? That website will book car and assignment driver depending client choose, a kind of primitive Uber but client should appointment at least one day ago. -
Django - Default value based on another model field
This is my existing django model class Account(models.Model): env = CharField(max_length=10) now I need to add period field to my model based on the value of the env field in model. I can get the period value based on the env from following dict in my settings file mydict = { 'dev':1, 'prd':2 } How do I add my period field to model? period = Integerfield(default=setvalue from dict) -
why are only some css classes being generated in tailwind?
I have a project where I'm using Django as backend and tailwind for the css. tailwind is not giving me any errors and is finding classes in my files but not generating the css. the only class that its working for is bg-blue-500 and nothing else. if anyone could think of why this may be happening or how to fix is I would really appreciate it. html page {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}Auctions{% endblock %}</title> <link rel="stylesheet" href="{% static 'auctions/output.min.css' %}"> </head> <body> <h1>Auctions</h1> <div> {% if user.is_authenticated %} Signed in as <strong>{{ user.username }}</strong>. {% else %} Not signed in. {% endif %} </div> <ul class="nav"> <li class="nav-item bg-red-500"> <a class="nav-link" href="{% url 'activeListings' %}">Active Listings</a> </li> {% if user.is_authenticated %} <li class="nav-item bg-blue-500"> <a class="nav-link" href="{% url 'logout' %}">Log Out</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'login' %}">Log In</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'register' %}">Register</a> </li> {% endif %} </ul> <hr> {% block body %} {% endblock %} </body> </html> tailwind.css @tailwind base; @tailwind components; @tailwind utilities; @layer base { h1 { @apply text-4xl; } h2 { @apply text-3xl; } h3 { @apply … -
I want to add this database of login users on my home page can anyone tell me how should i do this in python djago
[enter image description here][1] [1]: https://i.stack.imgur.com/qW49M.png this is the databasestrong text**** -
I am not able to use FPDF correctly in python in Django
Right now I need your help. When it comes to use fpdf in django I have several confusing problems, here I am going to give you my source code and you understand my situation. I tried several solutions but they were not proper clue. issue: I am going to create pdf and use method called FPDF().output("name.pdf") as it is, even I tried with open("name.pdf", mode="w") as file: as well and when i execute the FPDF().output("name.pdf") using django, it raises traceback called "no such file or drectory" Thanks from advance! class Resume: def __init__( self, personal_details: dict, work_experience: dict, education: dict, final_section: dict ): self.personal_details = personal_details self.work_experience = work_experience self.education = education self.final_section = final_section self.pdf_file = FPDF() def _normalize(self, slicer: str, limit: int) -> list: self.education = self.education summary = [] portion = '' temp = 0 for j in slicer.split(" "): if temp != limit: portion += j + " " else: summary.append(portion.strip()) portion = '' temp -= temp temp += 1 return summary def template_one(self, filename: str): path = str(pathlib.Path().resolve()).split("\\") full_path = "" for j in path: full_path += j + "/" personal_details_log = [ "Fullname:", "Email:", "Phone Number:", "City:", "Postal Code:" ] detail = [ "fullname", … -
How to Start Django Server on a remote host via robotframework .robot file?
How to Start Django Server on a remote host via robotframework .robot file? I tried robotframework-djangolibrary still not working on remote host, but local it's working. I tried executing manage.py runserver command but didn't work for remote again. Now in the picture i placed files in remote srever and executing this file automatically. Still no success enter image description here -
Why i can’t login using my login template
I am using a login template to log in to staff and non-staff members but the login page only allows the staff members or you can say superusers to login in which also logs me into the admin page, but I want to log in into the web app that I am using, not the admin page be it staff or non-staff for logging in. Is there any way to solve this issue? And yes I have already added: AUTH_USER_MODEL = "accounts.Account" LOGIN_REDIRECT_URL = "blogs" LOGOUT_REDIRECT_URL = "blogs" urls.py from django.urls import path from .views import CustomLogoutView, CustomRegistrationView, CustomLoginView urlpatterns = [ path("register/", CustomRegistrationView.as_view(), name="register"), path("login/", CustomLoginView.as_view(), name="login"), path("logout/", CustomLogoutView.as_view(), name="logout"), ] views.py from django.contrib.auth.views import LoginView, LogoutView from django.urls import reverse_lazy from django.views.generic import CreateView from accounts.models import Account from .forms import CustomRegistrationForm, CustomLoginForm class CustomRegistrationView(CreateView): model = Account form_class = CustomRegistrationForm success_url = reverse_lazy("login") redirect_authenticated_user = True template_name: str = "accounts/register.html" success_message = "You registered successfully." class CustomLoginView(LoginView): model = Account form_class = CustomLoginForm redirect_authenticated_user: bool = True success_url = reverse_lazy("dashboard") template_name: str = "accounts/login.html" class CustomLogoutView(LogoutView): template_name: str = "accounts/logout.html" next_page = None manager.py from django.contrib.auth.models import BaseUserManager class UserManager(BaseUserManager): def create_user( self, email, first_name, last_name, roll_no, … -
python virtual env overrides my ckeditor customized configuration
I need to customize my python-3.7/django-3.2/mezzanine-6.0/django-ckeditor-5.6.1 application just the same way as instructed here: how to add custom templates in django-ckeditor in django I modified the file <myStaticRoot>/ckeditor/ckeditor/plugins/templates/templates/default.js as explained, but didn't get the change in my web page before modifying also the corresponding file in my python virtual environment: <myvenv>/lib/python3.7/site-packages/ckeditor/static/ckeditor/ckeditor/plugins/templates/templates/default.js This is a very ugly trick, how can I prevent the python virtual environment from overriding my application specific settings ? -
To force use python3.9 after install libapache2-mod-wsgi-py3 django
I installed libapache2-mod-wsgi-py3 but It seems good for python3.6. My problem is set mod-wsgi for use python3.9 because my app django has all modules installed for this version. How can I do? I attach error log [Fri Oct 21 10:22:21.549718 2022] [wsgi:error] [pid 8227] mod_wsgi (pid=8227): Target WSGI script '/var/www/html/elastic_queries/python/djangosite/giustiziasite/giustiziasite/wsgi.py' cannot be loaded as Python module. [Fri Oct 21 10:22:21.549795 2022] [wsgi:error] [pid 8227] mod_wsgi (pid=8227): Exception occurred processing WSGI script '/var/www/html/elastic_queries/python/djangosite/giustiziasite/giustiziasite/wsgi.py'. [Fri Oct 21 10:22:21.550458 2022] [wsgi:error] [pid 8227] Traceback (most recent call last): [Fri Oct 21 10:22:21.550517 2022] [wsgi:error] [pid 8227] File "/var/www/html/elastic_queries/python/djangosite/giustiziasite/giustiziasite/wsgi.py", line 18, in <module> [Fri Oct 21 10:22:21.550522 2022] [wsgi:error] [pid 8227] application = StaticFilesHandler(get_wsgi_application()) [Fri Oct 21 10:22:21.550528 2022] [wsgi:error] [pid 8227] File "/usr/local/lib/python3.6/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Fri Oct 21 10:22:21.550532 2022] [wsgi:error] [pid 8227] django.setup(set_prefix=False) [Fri Oct 21 10:22:21.550537 2022] [wsgi:error] [pid 8227] File "/usr/local/lib/python3.6/dist-packages/django/__init__.py", line 24, in setup [Fri Oct 21 10:22:21.550541 2022] [wsgi:error] [pid 8227] apps.populate(settings.INSTALLED_APPS) [Fri Oct 21 10:22:21.550546 2022] [wsgi:error] [pid 8227] File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 114, in populate [Fri Oct 21 10:22:21.550550 2022] [wsgi:error] [pid 8227] app_config.import_models() [Fri Oct 21 10:22:21.550555 2022] [wsgi:error] [pid 8227] File "/usr/local/lib/python3.6/dist-packages/django/apps/config.py", line 301, in import_models [Fri Oct 21 10:22:21.550558 2022] [wsgi:error] [pid … -
Change select field options in client script in NetSuite
I have a client script runs on Suitelet. On Suitelet we have a sublist which has many select columns. Let's say we have Select 1 and Select 2. Select 2 options should be different if you change the option in Select 1. Could this be done in Client Script? or in that Suitelet? Any help would be appreciated. ` var select1= sublist.addField({ id: 'custpage_select1', label: 'Select1', type: ui.FieldType.SELECT }); var select2= sublist.addField({ id: 'custpage_select2', label: 'Select2', type: ui.FieldType.SELECT }); ` In client script when the field is changed, I want to change options of Select 2 depend on Select 1. function fieldChanged(scriptContext){ if(scriptContext.fieldId=="custpage_select1"){ let page = currentRecord.get(); var select2 = page.getField({fieldID:"custpage_select2"}); select2.removeSelectOption({value:"value1"}); } } But this shows me an error that Cannot read properties of null Thank you -
Django And Elasticsearch
I am evaluating the opportunity to include some elasticSearch indexes in our Django Backend, I reviewed so far three django apps: django-elasticsearch-dsl elasticsearch-django django-haystack So far, I can't tell if there is such a package not needing to replicate content of the indexes in the django DB, from what I read, it seems like we have to have some standard Relational DB ORM objects attached to each indexes. If I am right, that then implies the data duplication, and potentially a huge one in our case. Is there a way with the mentioned packages to avoid this objects duplication? Or did I misread the whole thing and it's not actually duplicating data? Thanks for your insights! Marc -
how to set values using aftersubmit function in create mode
I need to set the values while creating the inventory item form, I deployed the script in the corresponding form, and it is working as I tried to send an email. For this, it is working, But I don't know when I tried but nothing happened. <!-- /** *@NApiVersion 2.0 *@NScriptType UserEventScript */ define(["N/url", "N/record", "N/runtime"], function (url, record, runtime) { function afterSubmit(context){ var recordobj = context.newRecord; var Type=context.type; if(Type== context.UserEventType.CREATE) recordobj.setValue({ fieldId:'custitem27', Value:'something', }); } return{ afterSubmit:afterSubmit } }); --> -
How can i Migrate users from admin to my sqlite date base
i made the code to add users in the ADMIN panel, but i would like to have those users in a data base, how can i do that (could be in my data base sqlite made it by django? or i have to create a model to create users in my data base (but how can i login them after that)?