Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am currently working on a budget application in Django in which information is updated and saved through the handsontable spreadsheet
I created view function to save the data from handsontable but it keeps rendering the following error and I cannot find where the error is: Data to be sent: (4) [Array(10), Array(10), Array(10), Array(10)]0: (10) ['123', 'Office Expeses', 'Expenses', 1, 6, 7, 12, 13, 18, 57]1: (10) ['134', 'Other Expenses', 'Expenses', 2, 5, 8, 11, 14, 17, 57]2: (10) ['144', 'Office Supplies', 'Expenses', 3, 4, 9, 10, 15, 16, 57]3: (10) ['Column Total', '', '', 6, 15, 24, 33, 42, 51, 171]length: 4[[Prototype]]: Array(0) (index):243 POST http://127.0.0.1:8000/budgets/budgets/spreadsheet_view/23456/save_planning/ 500 (Internal Server Error) (anonymous) @ (index):243 (index):253 Network response was not ok. Status: 500 Internal Server Error (anonymous) @ (index):253 Promise.then (async) (anonymous) @ (index):251 (index):263 Fetch error: Error: Network response was not ok at (index):254:19 (anonymous) @ (index):263 Promise.catch (async) (anonymous) @ (index):262 (index):264 Error saving data: Error: Network response was not ok at (index):254:19 (anonymous) @ (index):264 Promise.catch (async) (anonymous) @ (index):262 I created the following view function: def save_planning(request, budget_code): print("Received POST request:", request.POST) if request.method == 'POST': try: data = json.loads(request.body) print("Received Data:", data) # Debug statement budget = Budget.objects.get(budget_code=budget_code) print("Budget:", budget) # Debug statement for item in data: print("Processing Item:", item) # Debug statement planning, created = … -
Getting id error in one of my views in django
I'm getting an error: TypeError: edit_book() got an unexpected keyword argument 'book_id' Exception Location: /...env/lib/python3.10/site-packages/django/contrib/auth/decorators.py, line 23, in _wrapper_view view: from .forms import BookForm @user_passes_test(user_in_book_store_staff_group) def add_book(request): if request.method == "POST": form = BookForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("books") else: form = BookForm() return render(request, "add_book.html", {"form": form}) url: path('edit_book/<int:book_id>/', views.edit_book, name='edit-book'), forms.py from django import forms from .models import Book, Author, Genre class BookForm(forms.ModelForm): class Meta: model = Book fields = '__all__' # Use all fields from the Book model widgets = { 'genre': forms.CheckboxSelectMultiple(), } I tried to set up a view without django form and also failed without decorator - same error. I'm VERY new to this, I'm jumping between youtube and chatGPT but I can't figure this one out, I'm not sure if I provided you with enough info. -
Load a dictionary into django model
I have a csv file that has multiple headers. I would like to get the data into a database using Django. The first token of each line indicates which type of event it is and identifying the table it needs to go in. I go through each line, matching up the headers and using a switch I’m ready to pass a correct dictionary to the model. I can’t finger out how to pass the dictionary into the model. I don’t want to go attribute by attribute because all the tables would be almost 10k lines of code. Is there a way to say Event_{type}.objects.create(my_dict) -
How to calculate the tax percentage in Django Query set?
Hello I m trying to calculate the invoice items total tax and final total amount no, invoice_code, tax_amount, net_amount Here model class PriceMaster(models.Model): status_type = ( ('a','Active'), ('d','Deactive') ) items = models.ForeignKey(Item, on_delete=models.CASCADE) gst = models.ForeignKey(Gst, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) status = models.CharField(max_length=1, choices=status_type, default = 'a') create_at = models.DateField(auto_now_add=True) update_at = models.DateField(auto_now=True) create_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) def __str__(self): return str(self.items) @property def cgst_unround(self): if not hasattr(self,'_cgst'): self._cgst = self.price * self.gst.gst / 100 return round(self._cgst,2) @property def per_gst(self): self.per = self.gst.gst / 2 return self.per @property def cgst(self): return round((self.cgst_unround / 2),2) @property def NetAmount(self): self.net_amount = self.price + self.cgst_unround return round(self.net_amount,2) class Invoice(models.Model): status_type = ( ('a','Active'), ('d','Deactive') ) invoice_no = models.CharField(max_length=200, default=None, null=True, blank=True) status = models.CharField(max_length=1, choices=status_type, default = 'a', blank=True) create_at = models.DateField(auto_now_add=True) update_at = models.DateField(auto_now=True) create_by = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return str(self.invoice_no) def InvoiceNoGenarat(sender, instance, created, *args, **kwargs): if created: quote_id = instance quote_obj = Invoice.objects.get(id = int(quote_id.id)) invoice_no = Invoice.objects.all().count() quote_query = Invoice.objects.filter(id = quote_id.id).update(invoice_no = str(invoice_no)) post_save.connect(InvoiceNoGenarat, sender = Invoice) class InvoiceItem(models.Model): quantity = models.IntegerField() items_price = models.ForeignKey(PriceMaster,on_delete=models.CASCADE) invoices = models.ForeignKey(Invoice, on_delete=models.CASCADE,null=True,blank=True) create_at = models.DateField(auto_now_add=True) create_by = models.ForeignKey(User, on_delete=models.CASCADE) Here my view.py I don't know how to make query def … -
I have a Django web app that relies heavily on third-party data. How to make the two sides independent but still usable?
I am building a web app using Django, but I have some doubts about the best architecture. The real-life scenario is more complex, but - for the sake of keeping it simple - let's use the example of a Fantasy Football app. There are two sides: the Football data (Matches, Clubs, Players, etc.) that comes from a third party API the Game data (Users, Fantasy leagues, Fantasy teams, etc.) that is generated inside the web app My first thought is that the Football data should be handled outside Django, for example having my ETL/ELT pipeline in phython scripts (e.g. using Polars) orchestrated using Airflow. In the real-life scenario there may be multiple sources, and the data could also be used for other purposes (e.g. analytics), so I think it would be best to keep it in a separate db that acts as my data warehouse. Also, this would make it so that the ETL process won't take away resources from the web app (although I guess I could achieve the same with e.g. Celery), and that I can keep my codebase separate. Question 1: Does this make sense? Second, I have the web app. I suppose that to use Football … -
Override Easy Thumbnails Dango File Type Setting
While using easy thumbnails in Dango I have set the default file type to webp. It works well. But on occasion I need it to ignore this setting. For example when I render an og image I would like it to stay as a PNG. Would it be possible to add an option to the template tag to use the default uploaded format and ignore the setting in the settings file? How would I code it, I'm guessing it would be some sort of override to the standard template tag or a new template tag that adds to the old template tag and calls it maybe. -
Django error "TemplateDoesNotExist" despite template existing
Trying to go through the cs50 web programming course and I've been stupidly stuck on one issue. I'm trying to render an entry template page if a title exists as defined by a get_entry variable and an error template if not. The branch: encyclopedia |-- templates |-- encyclopedia |-- error.html |-- entry.html |-- views.py |-- urls.py def entry(request, title): page = util.get_entry(title), if page == None: return render(request, "encyclopedia/error.html") else: return render(request, "encylopedia/entry.html") Environment: Request Method: GET Request URL: http://127.0.0.1:8000/wiki/css Django Version: 4.2.4 Python Version: 3.11.4 Installed Applications: ['encyclopedia', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template loader postmortem Django tried loading these templates, in this order: Using engine django: * django.template.loaders.app_directories.Loader: /Users/kajakubickova/cs50/wiki/encyclopedia/templates/encylopedia/entry.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/contrib/admin/templates/encylopedia/entry.html (Source does not exist) * django.template.loaders.app_directories.Loader: /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/contrib/auth/templates/encylopedia/entry.html (Source does not exist) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) ^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/kajakubickova/cs50/wiki/encyclopedia/views.py", line 16, in entry return render(request, "encylopedia/entry.html") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/shortcuts.py", line 24, in render content = loader.render_to_string(template_name, context, request, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ … -
How to add an existing field to form in Edit Binnacle?
I have a form where I must fill in the Control Center, Time, Type of Installation, Type of Events and Observation fields. Consider that installation_type and event_type are being stored in a binnacledailylogextension variable def new_log(request, system_nk, time_id, report_name): time = Time.objects.get(id=time_id) show_novelty_sen_v2 = time.date >= settings.START_DATE_NOVELTY_SEN_V2 title = 'Agregar nuevo registro' source = binnacle_source(time=time, report_name=report_name, system_nk=system_nk.upper()) class_form = source['formV2'] if show_novelty_sen_v2 else source['form'] form_note = BinnacleNoteForm data_post = _fix_date(data=request.POST.dict(), time=time) form = class_form( data_post or None, system_nk=system_nk.upper(), show_novelty_sen_v2=show_novelty_sen_v2, ) has_extra_hour = True if time.hours_in_day.count() == 25 else False if request.method == 'POST': form_note = form_note(data_post) if form.is_valid() and form_note.is_valid(): log = form.save(commit=False) log.note = form_note.save() if show_novelty_sen_v2: log.system = System.objects.get( natural_key=System.NaturalKeys.SEN) log.save() if data_post.get('report_name') == 'BinnacleEnergyEvent': event_history = create_event_history(log, 1) event_history.save() if data_post.get('event_type') != None or data_post.get('instalation_types') != None: event = request.POST['event_type'] installation = request.POST['installation_type'] binnacledailylogextension = create_binnacledailylogextension(log,event,installation) binnacledailylogextension.save() return HttpResponse( json.dumps({'reload': True}), content_type='application/json', ) return render(request, 'API/log_form.jade', { 'modal_title': title, 'form': form, 'form_note': form_note, 'has_extra_hour': has_extra_hour, 'time': time, 'report_name': report_name, 'method': 'POST', 'show_novelty_sen_v2': show_novelty_sen_v2, 'system_nk': system_nk, 'action': reverse( 'new_log', kwargs={ 'system_nk': system_nk.lower(), 'time_id': time.id, 'report_name': report_name, }, ) + '#report-name=' + report_name, }) Then when editing the form I can only edit the Control Center, Time and Observation … -
Database Connection Issue with Django createsuperuser Command
Getting a strange error when configuring Django. I have configured the database with host 0.0.0.0 in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xx', 'USER': 'xx', 'PASSWORD': 'xx', 'HOST': '0.0.0.0', 'PORT': '3306', } } When I do the migration python manage.py migrate it uses this host and account and sets the tables up. When I try to set up the superuser python manage.py createsuperuser I get a connectivity error: django.db.utils.OperationalError: (1045, "Access denied for user 'websiteuser'@'localhost' (using password: YES)") I'm not sure why this is trying to connect to localhost rather than the host in the settings file. Is there another settings file I've missed or do I need to provide a flag? -
Why do elements literally jump outside of their parents?
On this specific screen of an app I'm building, elements seem to and actually do escape their parent. I'm using Django, TailwindCSS and AlpineJS. But after some testing it's clear the problem doesn't belong to any of these frameworks. On the back-end, I'm looping over an array to render the courses inside a <section> inside <main>. The first one obeys fine. The second jumps to the div above main and the third goes all the way under <body> After removing both links to CSS and JS, the problem remains: So the problem isn't in either Tailwind or Alpine. So I checked the page sources, which are fine! The way they should be: I tested on Firefox Nightly, Edge and Brave, and they all behave the same. The loop in specif that is being run is this: {% for course in courses %} <div class="rounded-2xl bg-gray-100 shadow"> <header class="flex justify-between px-6 py-4" x-data="{ optOpen: false }" > <div> <h2>{{ course.name }}</h2> <span>Turno: {{ course.get_time_display }}</span> </div> <div> <button> <svg ...>...</svg> </button> <button @click="optOpen = !optOpen" class="relative"> <svg ...>...</svg> <div x-show="optOpen" class="absolute flex flex-col"> <button>Editar</button> <button>Excluir</button> </div> </button> </div> </header> <div>whats happening??</div> </div> {% endfor %} I don't know what else to … -
Changing the language, first response is 404 and after doing back getting the translated page
I'm really curious to know why it happens everytime, always after changing the laguage initialy getting the 404 page, and after doing back, getting the translated page. AND NOTE that it always happens every first time. What can be a problem? Example: here it is when I'm opening the page in browser: http://127.0.0.1:8000/ After changing to /fr: http://127.0.0.1:8000/fr # getting error because of absence '/' at the end After adding '/' everything works perfect: http://127.0.0.1:8000/fr/ I hope I could explain to you my bug. Any suggestions or advices, please? <ul class="dropdown-menu"> {% get_current_language as LANGUAGE_CODE %}</li> {% get_available_languages as LANGUAGES %}</li> {% get_language_info_list for LANGUAGES as languages%} {% for lang in languages%} <li> <a class="dropdown-item" href="/{{ lang.code }}{{ request.get_full_path|slice:"3:" }}**/**">{{ lang.code }}</a> </li> {% endfor %} </ul> -
Override Session Redirect URL timout Depends on User Type
I have this variable set on settings.py: SESSION_EXPIRE_AT_BROWSER_CLOSE = True SESSION_COOKIE_AGE = ( config('SESSION_COOKIE_AGE', cast=int, default=1200) # set just 1200 seconds (20 minutes) ) SESSION_SAVE_EVERY_REQUEST = True And I have these types of users: ADMINS_LOGOUT_REDIRECT_URL = reverse_lazy("admin_user_login") COMPANIES_LOGOUT_REDIRECT_URL = reverse_lazy("company_login") INDIVIDUALS_LOGOUT_REDIRECT_URL = reverse_lazy("login") I need to return the user to his login page after the session expired, Is there a way to override the logout of the session in Django or handle it by middleware or any idea can help me with this? -
Submit the form and debugging in Django
I want to create a form so that the user can register a product. However, the form is created but not submit. What is the reason? And when selecting the status, instead of the old version or the new version, n and o are recorded on the product page. Why? viws.py: create list @login_required(login_url="login") def create_list(request): if request.method == "POST": item = List() item.user = request.user.username item.title = request.POST["create_list_title"] item.category = request.POST["category"] item.status = request.POST["status"] item.description = request.POST["create_list_description"] item.first_bid = request.POST["create_list_initial_bid"] item.image_url = request.POST["img_url"] item.save() return redirect("index") return render(request, "auctions/create_list.html")` create_list.html: {% extends "auctions/layout.html" %} {% block body %} <h2 id = "h2">Create List</h2> <div> <form method="POST"> {% csrf_token %} <a id ="h4">Title : <input required placeholder="Title" autofocus type="text" name="create_title"/> <a id = "h4">Category : <input required placeholder="Category" type="text" name="category"/></a> <a id = "h4">Description : <textarea placeholder="Add Description" required type="text" name="create_desc"></textarea></a> <a id = "h4">Starting bid : <input required placeholder="Starting bid" type="number" name="create_initial_bid"/></a> <a id = "h4">Status : <input required placeholder="Status" type="text" name="status"/></a> <form action="upload.php" method="post" enctype="multipart/form-data"> <label id="h4" for="fileUpload">Upload Image:</label> <input id="h4" type="file" id="fileUpload" name="fileUpload"> </form><br> <a id = "h4">Image_url :<input placeholder="Image URL" type="text" name="img_url"/></a><br> <button id = "button" class="btn btn-outline-primary" type="submit">Submit</button> </form> </div> {% endblock %} models.py: class … -
Django and apexjs datetime issues
I try to view some date from the DB on an Apex Char it already worked but now I only get Date or Datetime issues so pls somebody can Help me with this. The Model that I am Using is this: class Temperature (models.Model): temperature = models.DecimalField(max_digits=5,decimal_places=2) sensor_id=models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['created'] Then I build view to get the Data sorted in all last6days ans last week: def temperature_all_data_view(request): data = Temperature.objects.all().values('created', 'temperature') data_list = [{'created': entry['created'].isoformat(), 'temperature': entry['temperature']} for entry in data] return JsonResponse(data_list, safe=False) def temperature_last_six_hours_data_view(request): six_hours_ago = datetime.now() - timedelta(hours=6) data = Temperature.objects.filter(created__gte=six_hours_ago).values('created', 'temperature') data_list = [{'created': entry['created'].isoformat(), 'temperature': entry['temperature']} for entry in data] return JsonResponse(data_list, safe=False) def temperature_last_seven_days_data_view(request): seven_days_ago = datetime.now() - timedelta(days=7) data = Temperature.objects.filter(created__gte=seven_days_ago).values('created', 'temperature') data_list = [{'created': entry['created'].isoformat(), 'temperature': entry['temperature']} for entry in data] return JsonResponse(data_list, safe=False) then I fetch the Data in JS and try to sort them into the ApexChart: let chart = null; async function fetchData(url) { const response = await fetch(url); const data = await response.json(); data.sort((a, b) => new Date(a.created) - new Date(b.created)); return data; } function renderChart(x_data, y_data, html_name) { if (chart) { chart.destroy(); } const options = { chart: { height: 300, … -
what does the order_qs[0] do in the following code, also can someone explain the following code to me
I am doing a project and have referred to someone else's code. But I am not able to understand the part after order_qs. can someone please it to me. There are some lines/functions that I am not able to understand. def add_to_cart(request, slug): item = get_object_or_404(Product, slug=slug) order_item, created = Cart.objects.get_or_create( item=item, user=request.user ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.orderitems.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() messages.info(request, "This item quantity was updated.") return redirect("mainapp:home") else: order.orderitems.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("mainapp:home") else: order = Order.objects.create( user=request.user) order.orderitems.add(order_item) messages.info(request, "This item was added to your cart.") return redirect("mainapp:home") -
Is it bad to run a fake initial migration during deployment? (Django)
When deploying my Django project, I kept getting this error: W: psycopg2.errors.DuplicateTable: relation "materials_location" already exists W: The above exception was the direct cause of the following exception: --snip-- W: django.db.utils.ProgrammingError: relation "materials_location" already exists While the problem seems self-explanatory, this error first started appearing after I manually altered the database when I had to rename apps and move models around apps. ("materials_location" was one of the things I'd added.) I eventually found this solution: running python manage.py migrate --fake-initial during the deploy hook (instead of just python manage.py migrate). This allowed Django... ...to skip an app’s initial migration if all database tables with the names of all models created by all CreateModel operations in that migration already exist. Problem solved. The rest of the migration was applied correctly (which included the addition of fields to the existing models) and the project was deployed without any errors. Is there a scenario where this solution could backfire down the line? Like, what if I deploy to a new server and make a brand new database? Or if I reset or squash migrations? I feel like this is safe, but straying from python manage.py migrate makes me uneasy. -
My django is no longer working because of the algorithm version not specified
I'm practicing creating a RESTAPI for ML model deploymentFrom this site. By repeating the various processes such as data migration and testing. I feel like I'm duplicating things. I even had to change the owner and relaunch the codes. I see that new endpoints, MLagorithm, MLalgorithmstatus are created instead of the old ones being overwritten (which is what I expected) HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "name": "random forest", "description": "Random Forest with simple pre- and post-processing", "code": "class RandomForestClassifier:\n def __init__(self):\n path_to_artifacts = \"../../research/\"\n self.values_fill_missing = joblib.load(path_to_artifacts + \"train_mode.joblib\")\n self.encoders = joblib.load(path_to_artifacts + \"encoders.joblib\")\n self.model = joblib.load(path_to_artifacts + \"random_forest.joblib\")\n\n def preprocessing(self, input_data):\n # JSON to pandas DataFrame\n input_data = pd.DataFrame(input_data, index=[0])\n # fill missing values\n input_data.fillna(self.values_fill_missing)\n # convert categoricals\n for column in [\n \"workclass\",\n \"education\",\n \"marital-status\",\n \"occupation\",\n \"relationship\",\n \"race\",\n \"sex\",\n \"native-country\",\n ]:\n categorical_convert = self.encoders[column]\n input_data[column] = categorical_convert.transform(input_data[column])\n\n return input_data\n\n def predict(self, input_data):\n return self.model.predict_proba(input_data)\n\n def postprocessing(self, input_data):\n label = \"<=50K\"\n if input_data[1] > 0.5:\n label = \">50K\"\n return {\"probability\": input_data[1], \"label\": label, \"status\": \"OK\"}\n\n def compute_prediction(self, input_data):\n try:\n input_data = self.preprocessing(input_data)\n prediction = self.predict(input_data)[0] # only one sample\n prediction = self.postprocessing(prediction)\n except Exception as e:\n return {\"status\": \"Error\", \"message\": … -
Django Compressor: multiple errors when ran but working fine
I have installed django-compressor==2.4.1 on my Django==2.2.28 project. As on the documentation, I installed it by putting compressor in my INSTALLED_APPS and added 'compressor.finders.CompressorFinder' to my STATICFILES_FINDERS. by now I am just trying it and using it on my base.html on the following: {% compress css %} <link rel="stylesheet" type="text/css" href="{% static 'css/survey.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'css/Roboto.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/AdminLTE.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/jquery.dataTables.min.css' %}"/> <link rel="stylesheet" type="text/css" href="{% static 'css/index.css' %}"/> {% endcompress %} And I enabled the following settings: # Django Compressor COMPRESS_ENABLED = True COMPRESS_OFFLINE = True COMPRESS_OFFLINE_TIMEOUT = 31536000 # 1 year in seconds but when I run manage.py compress the console is filled with errors, all about files that seem to be in the very same django-compressor folder. The compressed file gets made anyway and everything works fine. Here is the full output: https://pastebin.com/20kuHKLw Can anyone explain what is happening? -
Models aren't loaded yet wih django and celery
Hey i am using django and celery to run a app which seems to work fine all my tasks are picked up, but i cant seem to run the celery inspect command. I am using rabbitmq as my message broker which seems to work fine for sending and receiving tasks Django==3.2.19 celery==5.3.1 amqp==5.1.1 kombu==5.3.1 my celery.py looks like this, which has been copied mostly from the celery docs import os import celery from django import conf os.environ.setdefault(conf.ENVIRONMENT_VARIABLE, 'proj.settings') from django.conf import settings app = celery.Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) The error traceback that I am getting when running celery -A proj.celery inspect active not managed to find anything for models not being loaded, seems to be a lot of posts relating to apps not being loaded Traceback (most recent call last): File "/home/user/bin/celery", line 8, in <module> sys.exit(main()) File "/home/user/lib/python3.8/site-packages/celery/__main__.py", line 15, in main sys.exit(_main()) File "/home/user/lib/python3.8/site-packages/celery/bin/celery.py", line 217, in main return celery(auto_envvar_prefix="CELERY") File "/home/user/lib/python3.8/site-packages/click/core.py", line 1157, in __call__ return self.main(*args, **kwargs) File "/home/user/lib/python3.8/site-packages/click/core.py", line 1078, in main rv = self.invoke(ctx) File "/home/user/lib/python3.8/site-packages/click/core.py", line 1688, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "/home/user/lib/python3.8/site-packages/click/core.py", line 1434, in invoke return ctx.invoke(self.callback, **ctx.params) File "/home/user/lib/python3.8/site-packages/click/core.py", line 783, in invoke return __callback(*args, **kwargs) File "/home/user/lib/python3.8/site-packages/click/decorators.py", line … -
Saving objects related through many to many fields throwing field error
I have some models that are inter-related through various relations, including M2M relations. I have overridden create methods of 2 of the model's serializers so that I can create all the related objects through one post. But it keeps throwing the follwoing error :- { "permissions": { "ui_element": [ "Incorrect type. Expected pk value, received UIElement." ] }, "hospital": [ "Incorrect type. Expected pk value, received Hospital." ] } I can't for the life of me figure out how to solve this. Here's my models.py class StaffPermissions(TimeStampedModel): """ This table stores all the permissions that each staff has fields: - {ui_element}: foreign key to UIElement table - {create}: boolean field to store if the staff has create permission - {read}: boolean field to store if the staff has read permission - {update}: boolean field to store if the staff has update permission - {delete}: boolean field to store if the staff has delete permission """ ui_element = models.ForeignKey(UIElement, on_delete=models.CASCADE) create = models.BooleanField(default=False) read = models.BooleanField(default=False) update = models.BooleanField(default=False) delete = models.BooleanField(default=False) class HospitalDoctor(TimeStampedModel): """ This talbe stores all the information related to staff and their roles for a given hospital fields: - {hospital}: foreign key to Hospital table - {doctor}: … -
Django error: value must be either True or False
I'm currently having this error message on django: ["*** value must be either True or False."] It's really strange that I could not found where's the bug manager.py models.py from django.contrib.auth.base_user import BaseUserManager class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, password, email, **extra_fields): if not username or not password or not email: raise ValueError("All values must be filled!") if not password: raise ValueError("Password could not be empty!") user = self.model(username=username, email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(username, password, **extra_fields) def create_superuser(self, username, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(username, password, **extra_fields) models.py import hashlib import uuid from django.contrib.auth.models import AbstractUser from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from rest_framework.authtoken.models import Token import server.settings as settings from user.manager import UserManager STATUS_CHOICES = ( (0, "禁用"), (1, "启用"), ) class Users(AbstractUser): userid = models.AutoField(primary_key=True, verbose_name="用户ID", help_text="用户ID") username = models.CharField(max_length=150, unique=True, db_index=True, verbose_name="用户账号", help_text="用户名") email = models.EmailField(max_length=255, verbose_name="邮箱", null=True, blank=True, help_text="邮箱") avatar = models.CharField(max_length=255, verbose_name="头像", null=True, blank=True, help_text="头像", default="https://api.vvhan.com/api/qt?qq=771151240") VIP_CHOICES = ( (0, "普通用户"), (1, "VIP用户"), … -
Refactor or Relocation of data range validation in Views
im new to stack and dont know if its the best way to post, but im learning. I have a view in Django to validate dome data range fields that i have built with bootstrap, But im learning about managers, querysets and im trying to follow best practices. I feel that i can refactor this view, or shrink in size using forms and etc. Could you give me some tips? this views is large? can be refactored or relocated to other files, like forms? thanks in advance. https://github.com/paasxx/crypto-site/tree/sqlite_to_postgre/app_crypto def market(request, crypto): crypto_name = crypto crypto_model = getModelByName(crypto) sd = request.GET.get("startDate") ed = request.GET.get("endDate") min_date_table = crypto_model.crypto_objects.first_date().date max_date_table = crypto_model.crypto_objects.last_date().date crypto_data_all = crypto_model.crypto_objects.all_data() if sd == None and ed == None or sd == "" and ed == "": crypto_data = crypto_data_all context = { "currencies": currencies, "crypto": crypto_name, "crypto_data": crypto_data, "min_date_table": min_date_table, "max_date_table": max_date_table, } return render(request, "app_crypto/crypto_list.html", context) else: if datetime.strptime(ed, "%Y-%m-%d") < datetime.strptime(sd, "%Y-%m-%d"): messages.warning( request, "End Date must be greater than Start Date, Please try again." ) crypto_data = crypto_data_all context = { "currencies": currencies, "crypto": crypto_name, "crypto_data": crypto_data, "min_date_table": min_date_table, "max_date_table": max_date_table, } return render(request, "app_crypto/crypto_list.html", context) else: if sd == None or sd == "": … -
django Strings must be encoded before chechking?
i have a register form it work well and when i login the user it says that 'strings must be encoded before chechking ; and the error always show in login bcrypt.chekwp def getregisterpage(request): if request.method == "POST": firstname=request.POST.get('firstname') lastname=request.POST.get('lastname') email = request.POST.get("email") password = request.POST.get("password") hashed_password = bcrypt.hashpw(password.encode('utf-8'),bcrypt.gensalt()) if firstname and lastname and email and password : data=User(firstname=firstname,lastname=lastname,email=email,password=hashed_password) data.save() return redirect('login') else: return render (request,'register.html') ef getloginpage(request): if request.method == "POST": email = request.POST.get("email") password = request.POST.get("password") try: user = User.objects.get(email=email) except User.DoesNotExist: return redirect('register') if bcrypt.checkpw(password.encode('utf-8'),user.password): authenticated_user = authenticate(request,email=email,password=password) if authenticated_user: login(request, authenticated_user) messages.success(request, 'Logged in Successfully.') return redirect("home") else: messages.error(request, 'Authentication failed') else: messages.error(request, 'Invalid email or password.') return render(request, "login.html") -
When i try to login through new user and try to update its balance it is giving me {"detail": "User not found", "code": "user_not_found"} this error
My transaction API that i created where is this error occuring My serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'password', 'gender', 'age'] class LoginSerializer(serializers.ModelSerializer): username = serializers.CharField(required=True) password = serializers.CharField(required=True) class Meta: model = User fields = ['username', 'password'] class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ['account_id', 'account_no', 'balance'] class TransactionSerializer(serializers.ModelSerializer): class Meta: model = Transaction fields = ['account_id', 'transaction_type', 'transaction_balance'] My Views in Apps # only use serializer here in request body and response @swagger_auto_schema(method="post", request_body=LoginSerializer, responses={"200": 'LoginSerializer'}, operation_id="user Login", ) @api_view(['POST']) @permission_classes([AllowAny]) def login(request): # user can sign_in through this API serializer = LoginSerializer(data=request.data) if serializer.is_valid(): username = serializer.validated_data['username'] password = serializer.validated_data['password'] user_obj = User.objects.get(username=username, password=password) refresh = RefreshToken.for_user(user_obj) return Response({'msg': 'Logged In', 'refresh': str(refresh), 'access': str(refresh.access_token)}) return Response(serializer.errors) @swagger_auto_schema(method="post", request_body=TransactionSerializer, responses={"200": 'TransactionSerializer'}, operation_id="user signup transaction", ) @api_view(['POST']) # @authentication_classes(JWTAuthentication) # @permission_classes(IsAuthenticated) def transaction(request): # all read and update of balance logic here from this API serializer = TransactionSerializer(data=request.data) token = request.headers.get('Authorization') new_token = token.split(" ") decode_payload = jwt.decode(jwt=new_token[1], key=SECRET_KEY, algorithms=['HS256']) user = decode_payload['user_id'] if serializer.is_valid(): user_id = user transaction_type = serializer.validated_data['transaction_type'] acc_id = serializer.validated_data['account_id'] tran_bal = serializer.validated_data['transaction_balance'] if transaction_type == Transaction.TransactionType.DEPOSIT: acc_balance = Account.objects.get(id=acc_id.id, user_id=user_id) acc_balance.balance = acc_balance.balance … -
DJANGO: Query for select_related in view shows error
In my project with this ERM: I need to add equipment to an institute. Tried this: class EquipmentinLocationAdd(CreateView): model = EquipmentInstitute, Lot form_class = EquipmentInstituteForm template_name = 'Procure/equipmentininstitute_add.html' def get_success_url(self): return reverse('equipmentinstitute_sys', kwargs={'pk':self.object.Institute_id}) def get_initial(self): qs = Institute.objects.get( id = self.kwargs['pk'] ) initial = {'Institute': qs} return initial def get_context_data(self, **kwargs): # query for Institute Var1 = Institute.objects.all().get( id = self.kwargs['pk'] ) # query for Project Var4 = Project.objects.get(id = 5) # Here is my problem context = super().get_context_data(**kwargs) context ['queryset2'] = Lot.objects.all().values_list("LotTitle","Project") context.update({'LOK': Var1, 'LOKID': Var1.id, 'PR_id':Var4.id, 'PR':Var4}) return context Var1 is delivering data of the related institute. Var4 is supposed to get the related project. For testing purposes I worked with an fix 'id' of 5 However I need the related project of the selected institute but all my query efforts failed to retrieve the related project_id. (See Var4 in code) Need help! Thanks in advance Ben