Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Class Media js Refused to execute script from because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled
when importing a local js file to add javascript functionalities to admin, you may face this error: Refused to execute script from 'http://localhost:8080/' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled. -
Django - form making one parent object and multiple child objects
I'm trying to make a Django model based form which will allow to create two models which one will be passed as a foreign key to second one. models.py class Recipe(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Ingredient(models.Model): name = models.CharField(max_length=200) quantity = models.CharField(max_length=200) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) def __str__(self): return self.name forms class IngredientForm(ModelForm): class Meta: model = Ingredient fields = ['name', 'quantity'] class RecipeForm(ModelForm): class Meta: model = Recipe fields = ['name'] and views.py ---- here is the problem def new_recipe_create_view(request, *args, **kwargs): context = {} created_recipe = None form = RecipeForm() if request.method == 'POST': form = RecipeForm(request.POST) if form.is_valid(): print("recipe successfully created") form.save() name = form.data['name'] created_recipe = Recipe.objects.filter(name=name).last() #new recipe is being made correctly IngredientFormSet = inlineformset_factory(Recipe, Ingredient, fields=('name', 'quantity'), extra=3, max_num=10, labels = { 'name': (''), 'quantity': (''), }) if request.method == 'POST': formset = IngredientFormSet(request.POST, instance=created_recipe) if formset.is_valid(): formset.save() else: print("formset is not valid") # <------------------------------------------ else: formset = IngredientFormSet( instance=created_recipe) if form.is_valid() and formset.is_valid(): return redirect('index') context['formset'] = formset context['form'] = form return render(request, 'recipes/create_recipe.html', context) part with inlineformset_factory, I made following docs: https://docs.djangoproject.com/en/4.1/topics/forms/modelforms/#inline-formsets chapter: Using an inline formset in a view but it does not work --> formset.is_valid() is … -
KeyError when importing config.ini file into Management Command folder and running manage.py (Django)
I have the follow structure. members ├── management │ │── __init__.py │ │── commands │ │── active.py │── whatsapp.py │── config.ini I am trying to run a whatsapp api and I have all my authentication data stored in a config.ini file. However, when I run python manage.py active I get the following error message. C:\Users\timmeh\source\Python Projects\Django Projects\env\myproject\topxgym>python manage.py active Traceback (most recent call last): File "C:\Users\timmeh\source\Python Projects\Django Projects\env\myproject\topxgym\manage.py", line 22, in <module> main() File "C:\Users\timmeh\source\Python Projects\Django Projects\env\myproject\topxgym\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\timmeh\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\timmeh\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\timmeh\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\timmeh\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) File "C:\Users\timmeh\source\Python Projects\Django Projects\env\myproject\topxgym\members\management\commands\active.py", line 20, in handle msg = WhatsApp(name, phone, date) File "C:\Users\timmeh\source\Python Projects\Django Projects\env\myproject\topxgym\members\management\commands\whatsapp.py", line 14, in __init__ self.authorization = self.config['Auth']['Authorization'] File "C:\Users\timmeh\AppData\Local\Programs\Python\Python310\lib\configparser.py", line 964, in __getitem__ raise KeyError(key) KeyError: 'Auth' The code works fine if I move it to a separate folder and run the whatsapp.py file directly. active.py file from turtle import update from django.core.management.base import BaseCommand, CommandError from members.models import ActiveMember from datetime import datetime, timedelta from .whatsapp import WhatsApp class Command(BaseCommand): help = 'Deactivate expired memberships!' def handle(self, *args, … -
in _validate_username AttributeError: 'Manager' object has no attribute 'get_by_natural_key' error
model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from .managers import UserAccountManager class UserAccount(AbstractBaseUser, PermissionsMixin): email = models.EmailField( max_length=255, unique=True, # null=False, # blank=False, verbose_name="email", ) name = models.CharField(max_length=255) is_active=models.BooleanField( default=True, ) is_staff=models.BooleanField( default=False, ) is_admin=models.BooleanField( default=False, ) created_at=models.DateTimeField(auto_now_add=True) objects: UserAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['name'] def __str__(self): return self.email managers.py ''' from django.contrib.auth.models import BaseUserManager class UserAccountManager(BaseUserManager): def create_user(self, email, name, password=None): """ Creates and saves a User with the given email, name and password. """ if not email: raise ValueError('Users must have an email address') email=self.normalize_email(email) email = email.lower() user = self.model( email=email, name=name ) user.set_password(password) user.save(using=self._db) return user def create_admin(self, email, name, password=None): """ Creates and saves a superuser with the given email, name and password. """ user = self.create_user(email, name, password) user.is_admin = True user.is_staff = True user.save(using=self._db) return user def create_superuser(self, email, name, password=None): """ Creates and saves a superuser with the given email, name and password. """ user = self.create_user(email, name, password) user.is_staff = True user.is_admin = True user.is_superuser = True user.save(using=self._db) return user ''' -
I want to group an entity based on one foreign key relation in rest django
I have two model here and records are related to employee class Employee(models.Model): name = models.CharField(max_length=100) position = models.CharField(max_length=100) site = models.CharField(max_length=100) wage = models.DecimalField(max_digits=4, decimal_places=0, default=0) class Record(models.Model): employee = models.ForeignKey(Employee, related_name='employee', on_delete=models.DO_NOTHING) date = models.DateField() cash = models.DecimalField(max_digits=4, decimal_places=0, default=0) I would like to generate a which list all records of each employees Something like below { "id": 1, "name": "John Doe", "position": "manager", "Records": [ { "date": "2020-12-09T18:30:00.000Z", "cash": 888 }, { "date": "2020-10-10T18:30:00.000Z", "cash": 999 } ] } Please help me to write the serialiser and view set for my above requirement. -
I'm Unable to setup all the configuration for using django-smart-selects
i'm unable to setup all the things require for using ChainedForeignKey from smart_selects like what to add in urls.py and in settings.py and in models.py and etc ... please anyone who can help me in this .. -
Django suddenly raises `OSError: [Errno 22] Invalid argument` and dev server doesn't work anymore
I made some changes to a html file and suddenly my django app stopped loading with the dev server returning OSError: [Errno 22] Invalid argument. I never had such situation in years of Django coding and don't know how to further investigate / fix this? I shut all sessions/tabs etc. and restarted the dev server without success. This is what I get when starting dev server: Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). August 20, 2022 - 18:25:13 Django version 4.1, using settings 'cherry.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. [20/Aug/2022 18:25:25] "GET / HTTP/1.1" 200 10645 [20/Aug/2022 18:25:25] "GET /static/css/dist/styles.css HTTP/1.1" 304 0 This is the traceback Traceback (most recent call last): File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/wsgiref/handlers.py", line 138, in run self.finish_response() File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/wsgiref/handlers.py", line 184, in finish_response self.write(data) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/wsgiref/handlers.py", line 293, in write self._write(data) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/wsgiref/handlers.py", line 467, in _write result = self.stdout.write(data) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/socketserver.py", line 826, in write self._sock.sendall(b) OSError: [Errno 22] Invalid argument [20/Aug/2022 18:34:49,657] - Broken pipe from ('127.0.0.1', 63773) -
Reverse resolution of URLs in Django with multiple url parameters
In my blog app I need to show articles based on the url: app_name = 'blog_app' urlpatterns = [ path('<int:user_id>/<int:year>/<int:month>', views.IndexView.as_view(), name='index'), path('<int:user_id>/<int:year>/<int:month>/<int:article_id>', views.DetailView.as_view(), name='detail'), ] The structure of the project is: myblog points to portal (for login); after login portal points to blog_app (which contains the articles list). So the steps to show articles are: mysite_index --> portal_login --> blog_app_index In portal app, after login, using a button I want to go to the index view of blog_app. So I need to specify all url parameters, and I'm trying to do it in this way: {% if user.is_authenticated %} <a href=" {% url 'blog_app:index' user_id = user.id year = {% now "Y" %} month = {% now "m" %} %} "> <button class="btn btn-secondary" type="button">Go</button> </a> {% endif %} I don't know why the URL becomes: http://127.0.0.1:8000/portal/%7B%25%20url%20'blog_app:index'%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20user_id%20%3D%20user.id%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20year%20%3D%202022%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20month%20%3D%2008%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%25%7D What I'm doing wrong? How I should do this type of reversing? -
Using threading.local() in a kubernetes container
I have a middleware in my app that sets the currently logged in user. On my local machine, get_current_user() works fine, but it seems to return None when the app is run in a kubernetes container. What am I missing?: USER_ATTR_NAME = getattr(settings, "LOCAL_USER_ATTR_NAME", "_current_user") _thread_locals = local() def _do_set_current_user(user_fun): setattr(_thread_locals, USER_ATTR_NAME, user_fun.__get__(user_fun, local)) def _set_current_user(user=None): """ Sets current user in local thread. Can be used as a hook e.g. for shell jobs (when request object is not available). """ _do_set_current_user(lambda self: user) class SelfServeCurrentUserMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): # request.user closure; asserts laziness; # memorization is implemented in # request.user (non-data descriptor) _do_set_current_user(lambda self: getattr(request, "user", None)) response = self.get_response(request) return response def get_current_user(): current_user = getattr(_thread_locals, USER_ATTR_NAME, None) if callable(current_user): return current_user() return current_user def get_current_authenticated_user(): current_user = get_current_user() if isinstance(current_user, AnonymousUser): return None return current_user -
HTTPResponse.__init__() got an unexpected keyword argument 'content_type'
Error - TypeError at /api/ HTTPResponse.init() got an unexpected keyword argument 'content_type' Request Method: GET Request URL: http://127.0.0.1:8000/api/ Django Version: 4.0.5 Exception Type: TypeError Exception Value: HTTPResponse.init() got an unexpected keyword argument 'content_type' Exception Location: D:\Python_Tutorials\DJango\PracticeDjango\Rest_Practice\withoutrest\testapp\views.py, line 17, in emp_data_json_view Python Executable: C:\Users\HP\AppData\Local\Programs\Python\Python310\python.exe Python Version: 3.10.5 Python Path: ['D:\Python_Tutorials\DJango\PracticeDjango\Rest_Practice\withoutrest', 'C:\Users\HP\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\HP\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\HP\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\HP\AppData\Local\Programs\Python\Python310', 'C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages', 'C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\win32', 'C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\win32\lib', 'C:\Users\HP\AppData\Local\Programs\Python\Python310\lib\site-packages\Pythonwin'] Server time: Sat, 20 Aug 2022 17:29:03 +0000 from http.client import HTTPResponse from django.shortcuts import render import json # Create your views here. def emp_data_json_view(request): emp_data = {'eno': 100, 'ename':'sunny', 'esal' : 1000, 'address' : 'Pune' } # dumps() -> coonvert python dict to json # loads() -> convert json to python dict #converting pytohn dictionary to json data json_data = json.dumps(emp_data) # if we did not mention content type - it will be consider as HTTP response only return HTTPResponse(json_data, content_type = 'application/json') -
The form did't send the data to the back end in Django customize form
I am trying to customize the ModelMultipleChoiceField in the form but when I am trying to submit the form I get error Enter a list of values my form.py class AppointmentCreateViewForm(forms.ModelForm): patient= forms.ModelChoiceField( queryset=Patient.objects.all(),label="Patient") appointmentDate = forms.DateField(label="Appointment date", widget=forms.DateInput(format='%Y-%m-%d')) appointmentType = forms.ChoiceField(choices=AppointmentTypes, required=False, label="Appointmen type") appointmentStatus = forms.ChoiceField(label="Appointment Status", choices=AppointmentStatuss) operation = forms.ModelMultipleChoiceField(widget=forms.Select(attrs={ 'class': 'js-example-basic-multiple', 'name': 'states[]', 'multiple': 'multiple' }), queryset=Operation.objects.all(),label="Operation") class Meta: model = Appointment fields = ('patient', 'appointmentDate', 'appointmentType','appointmentStatus','operation') my html <section> <form action="" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Save" /> </form> </section> -
Get updated session data in a Django Channels' consumer
Django Channels documentation says the following regarding session persistence: If you are in a WebSocket consumer, however, the session is populated but will never be saved automatically - you must call scope["session"].save() However, I noticed that it doesn't work the other way aroung, e.g. if session data gets modified by a view, those changes don't affect the version of the session state accessible from inside a consumer (even with request.session.modified = True applied) -
Reading same matches of using regex and storing in csv in multiple line
I have a txt file : Your Name: Arya Arjun Subject Name : Math Your Name: Arya Arvind Subject Name : Science I am using a regex to get the name : ^Your Name:[\S](.) Code : filename = "Path/File.txt" fo = open(filename, 'r') lines = fo.readlines() name = "" for line in lines: match = re.findall("^Your Name:[\S]*(.*)", line) if len(match) > 0: name += ",".join(match) print("-----------Your Name------------") print("name :",name) O/P > name : Arya Arjun Arya Arvind so Its storing the name in csv like below. Now I'm storing the result(names) in a csv file but its storing like this : I need to save it like this: Please let me know if any updates. -
When celery worker is started, it throws botocore.exceptions.NoCredentialsError: Unable to locate credentials -Django
I have digital ocean spaces configured to which i connect with the api keys. I have defined the api key in a .env. I have made a different module where I am getting the values as shown below conf.py AWS_ACCESS_KEY_ID= os.environ.get("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY= os.environ.get("AWS_SECRET_ACCESS_KEY") and this module is then imported in the settings file like below settings.py from .cdn.conf import ( AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, ) AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY Now when I run python manage.py runserver I get no error. But when I am trying to run the celery worker command celery -A proj.celery worker --pool=solo -l INFO, I get this error raise NoCredentialsError botocore.exceptions.NoCredentialsError: Unable to locate credentials the entire traceback Traceback (most recent call last): File "C:\Users\rickb\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\rickb\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\rickb\Envs\solvelitigationdrf-env\Scripts\celery.exe\__main__.py", line 7, in <module> File "C:\Users\rickb\Envs\solvelitigationdrf-env\lib\site-packages\celery\__main__.py", line 15, in main sys.exit(_main()) File "C:\Users\rickb\Envs\solvelitigationdrf-env\lib\site-packages\celery\bin\celery.py", line 217, in main return celery(auto_envvar_prefix="CELERY") File "C:\Users\rickb\Envs\solvelitigationdrf-env\lib\site-packages\click\core.py", line 1130, in __call__ return self.main(*args, **kwargs) File "C:\Users\rickb\Envs\solvelitigationdrf-env\lib\site-packages\click\core.py", line 1055, in main rv = self.invoke(ctx) File "C:\Users\rickb\Envs\solvelitigationdrf-env\lib\site-packages\click\core.py", line 1657, in invoke return _process_result(sub_ctx.command.invoke(sub_ctx)) File "C:\Users\rickb\Envs\solvelitigationdrf-env\lib\site-packages\click\core.py", line 1404, in invoke return ctx.invoke(self.callback, **ctx.params) File "C:\Users\rickb\Envs\solvelitigationdrf-env\lib\site-packages\click\core.py", line 760, in invoke return __callback(*args, **kwargs) File "C:\Users\rickb\Envs\solvelitigationdrf-env\lib\site-packages\click\decorators.py", line 26, … -
how can I get original text which is Bangla Language value 2 or more pdf in array?
when I upload 2 or more bangla pdf then it will conver into pdf every page as image then all image convert into text. But When a pdf convert complete into text then this all text puting an Array like file name as key and all text as a balue then tokenizing all of then using nltk. But I did'n store into array as same text. there are showing some garbage. for pdf in request.FILES.getlist("files"): pdf_name = pdf.name array_of_all_text = [] if pdf: image_file_list = [] all_text = '' with TemporaryDirectory() as tempdir: pdf_pages = convert_from_bytes(pdf.read()) for page_enumeration, page in enumerate(pdf_pages, start=1): filename = f"{tempdir}\page_{page_enumeration:03}.jpg" page.save(filename, "JPEG") image_file_list.append(filename) else: for image_file in image_file_list: text = pytesseract.image_to_string(Image.open(image_file),lang="ben") text = text.replace('\n', ' ') all_text += text hello_world = sent_tokenize(all_text) array_of_all_text.append(hello_world) else: return HttpResponse('this is not a pdf') return HttpResponse(array_of_all_text) This code output like ['সত্য সেলুকাস নীরেন্দ্রনাথ চক্রবর্তী থাকা মানে থাকা মানে কিছু বই, থাকা মানে লেখার টেবিল, থাকা মানে আকাশের নীল, ছাতের কার্নিসে দুটি পাখি, একা-নৌকাটির ক্রমে দৃষ্টির আড়ালে চলে যাওয়া। ভাদ্রের গুমট ভেঙে বৃষ্টির খবর নিয়ে ছুটে আসে হাওয়া, যা এসে বুকের মধ্যে লাগে। থাকা মানে মানুষের মুখ, ঘাম, ক্লান্তি ও বিষাদ, যা নিয়ে সংসার, তার সবই। থাকে মানে দুঃখ-সুখে, সংরাগে-বিরাগে … -
Django Flutter Ecommerce Shopping Cart
I am attempting to build an ecommerce site with a functional shopping cart that does not require a user to login before adding/removing items. To add this functionality I plan to store information based around the user's device to remember their order history, current items in cart, etc. For this, I am using a python Django backend (Django Rest Framework) and a Dart Flutter front end. This is going to be solely a web application to start and then cross into a mobile application, hence why I am using flutter. My question is more of a general architecture question rather than specific coding. I have done a lot of research as to how to grab a device ID using the flutter front end and then send that device ID to the backend Django application through a cookie. My question is if this is the right direction to go? Do I use flutter to create the cookie and then send it via POST request to the backend to manage the shopping cart? Or do I create the device ID through django backend some how? Any help would be appreciated. Thanks. -
Object of type Email is not JSON serializable, How to create or update Django model object
I'm trying to build an object from my Email model, if the 'user_email' which is a user_email = models.CharField(primary_key=True, max_length=200) already exists just update it, if it doesn't exist create a new one I show you how I create my new object. I get the following error: TypeError: Object of type Email is not JSON serializable My models.py extract: class Email(models.Model): user_email = models.CharField(primary_key=True, max_length=200) user_phone_number = models.IntegerField() user_device_id = models.CharField(max_length=200)#request.META.get('HTTP_DEVICE', '') lat = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) lng = models.DecimalField(max_digits=22, decimal_places=16, blank=True, null=True) user_address = models.CharField(max_length=200) creation_date = models.DateTimeField(default=None) email_status = models.BooleanField(default=False) email_score = models.IntegerField() valid_email = models.BooleanField(default=False) fraud = models.BooleanField(default=False) My views.py extract: class UserListView(APIView): serializer_class = EmailSerializer queryset = Email.objects.all() pagination_class = StandardResultsSetPagination def get_serializer_class(self): if self.action == 'list': return EmailListSerializer return EmailSerializer def post(self, request, *args, **kwargs): parametros = request.POST email='email=' + request._full_data['user_email'] response = UserConnector(email).get_user_data() obgs = response[1]['results'] if len(obgs) == 0: user_email = self.request.POST.get('user_email') email_stat = '' email_scor = '' email_valid = '' frau = '' else: obg = response[1]['results'][0] user_email = self.request.POST.get('user_email') email_stat = obg.get('email_status') email_scor = obg.get('email_score') email_valid = obg.get('valid_email') frau = obg.get('fraud') NewEmail = Email( user_email = user_email, user_phone_number = self.request.POST.get('user_phone_number'), user_device_id = request.META.get('HTTP_DEVICE', ''), lat = self.request.POST.get('lat'), lng = self.request.POST.get('lng'), … -
How to set up a callable for Django Imagefield's >> default << parameter
So I have a Model that contains a couple hundred instances and I now added an imagefield logo. As I don't want to upload each and every logo via the admin manually, I want to set up a callable that returns the correct file path so I can just push all logos to media/company_logos. # models.py def logo_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return f'company_logos/{instance.symbol}' class Company(models.Model): symbol = models.CharField(max_length=50) logo = models.ImageField(upload_to='company_logos/', default=logo_directory_path(instance=symbol, filename=f'{symbol}.png')) This returns an error at instance=symbol saying Type 'str' doesn't have expected attribute 'symbol' Another approach was logo = models.ImageField(upload_to='company_logos/', default=f'company_logos/{symbol}') which returns a URL as src="/media/company_logos/<django.db.models.fields.CharField>" I am not quiet sure how to set this up as I cant fully understand the official docs. My desired outcome is to have a URL for default like so: company_logos/IBM.png with field symbol being the corresponding part (I tried it via f-string). -
Django How to retrieve data based on their pk
I want a staff Dashboard which can see all user data and also CRUD it. how can I dynamically filter for the pk of the user data. If I use objects.all I get everything but cant edit specific values from django.contrib.auth.mixins import UserPassesTestMixin class AdminStaffRequiredMixin(LoginRequiredMixin, UserPassesTestMixin): def test_func(self): return self.request.user.is_superuser or self.request.user.is_staff class Dashboard (AdminStaffRequiredMixin, LoginRequiredMixin, ListView): model = SchulverzeichnisTabelle template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['Schulverzeichnis'] = SchulverzeichnisTabelle.objects.all() return context -
Django migrate ValueError: too many values to unpack
Calling python manage.py migrate results in the following error for the auth table. I've tried deleting my DB and all migrations to start from scratch, not sure where the issue is coming from. Django version is 4.1 $ python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, generator, sessions Running migrations: Applying auth.0001_initial...Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "<redacted>/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_lin e utility.execute() File "<redacted>/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "<redacted>/venv/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "<redacted>/venv/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "<redacted>/venv/lib/python3.8/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "<redacted>/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "<redacted>/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "<redacted>/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "<redacted>/venv/lib/python3.8/site-packages/django/db/migrations/executor.py", line 255, in apply_migration migration_recorded = True File "<redacted>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/schema.py", line 39, in __exit__ self.connection.check_constraints() File "<redacted>/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 289, in check_constraints for column_name, ( ValueError: too many values to unpack (expected 2) Any help is appreciated! -
import module in Django
I have a project with structure like on this picture. Folders structure Where 'backend' folder is Django project folder. I need to import module from another folder 'main' inside Django app file, i.e. import main.Text_Generator in backend.app.views file. I tried: from ...main.Text_Generator import *. This raise an error: "attempted relative import beyond top-level package" And from main.Text_Generator import *, also error "No module named 'main'" What is the correct way to do such import? -
How save edit form in multilanguage project
I'm studying Django from the book Django 2 by Examples. I'm trying to improve a project which starts in chapter 10. Now, I'm trying to add multilingualism with the help of "django-parler". In general I did it, but it seems to me that there are better ways. Views are implemented as classes that are inherited from mixins. If a language other than the default language is selected on the page, the form still comes with the value of laguage_code field equal to default. I tried unsuccessfully to change this field in the form_valid method. The form was still saved with the default language. The only option that works for me is this, by it looks like kludge: def form_valid(self, form): language = translation.get_language() _course = form.save(commit=False) try: course = Course.objects.get(pk=_course.id) except Course.DoesNotExist: course = Course() course.owner = self.request.user course.set_current_language(language) cd = form.cleaned_data course.subject = cd['subject'] course.title = cd['title'] course.slug = cd['slug'] course.overview = cd['overview'] course.save() return redirect(reverse('courses:manage_list')) Maybe someone knows a more elegant way to implement this? I will be grateful. -
POST from Python file to Database in Django
I am developing an application in Django which uses machine learning. For now, I have trained the model and have created a list in views.py . However, I would like to POST the prediction from the file to the database. I've checked many tutorials and even StackOverflow, but I haven't got a satisfactory answer. Here is my views.py: from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from core.models import Churn from core.serializers import ChurnSerializer from django.http.response import JsonResponse import pickle # Create your views here. #GET, POST, PUSH, DELETE methods defined u/csrf_exempt def churnApi(request,id=0): if request.method=='GET': churns = Churn.objects.all() churns_serializer = ChurnSerializer(churns, many=True) return JsonResponse(churns_serializer.data, safe=False) elif request.method=='POST': churn_data=JSONParser().parse(request) churns_serializer = ChurnSerializer(data=churn_data) if churns_serializer.is_valid(): churns_serializer.save() return JsonResponse("Added Successfully!", safe = False) return JsonResponse("Failed to Add", safe=False) elif request.method=='PUT': churn_data = JSONParser().parse(request) churn=churns.objects.get(ModelPred=churn_data['ModelPred']) churns_serializer=ChurnSerializer(churn,data=churn_data) if churns_serializer.is_valid(): churns_serializer.save() return JsonResponse("Updated successfully", safe=False) return JsonResponse("Failed to update", safe=False) elif request.method=='DELETE': churn=Churn.objects.get(ModelPred=id) churn.delete() return JsonResponse("Deleted successfully", safe=False) #Render frontend from folder def front(request): context = { } return render(request, "index.html", context) #Prediction generated by Machine Learning model def result(request): cls = pickle.load('churn_model.sav') lis = [] lis.append(request.GET['0']) lis.append(request.GET['1']) lis.append(request.GET['29.85']) lis.append(request.GET['29.85']) lis.append(request.GET['0']) lis.append(request.GET['1']) lis.append(request.GET['0']) lis.append(request.GET['0']) lis.append(request.GET['0']) lis.append(request.GET['1']) lis.append(request.GET['1']) lis.append(request.GET['1']) lis.append(request.GET['0']) lis.append(request.GET['0']) lis.append(request.GET['1']) … -
HTMX infinite-scroll cards changing shapes after scrolling
i'm trying to use htmx's infinite scroll but it doesn't work properly <body> <div class="container"> {% block content %} <div {% if products.has_next %} hx-get="?page={{ products.next_page_number }}" hx-trigger="revealed" hx-swap="afterend" {% endif %} > {% include 'includes/cards.html' %} </div> {% include 'includes/sidebar.html' %} {% endblock content %} </div> </body> when i scrolled down product cards sliding to right slightly and gets smaller on mobile like this and this: to this : can you guys help me understand what im doing wrong please? i also tried https://infinite-scroll.com/ its perfectly working. Edit: views.py def shop(request): anabanner = AnaBanner.objects.all() gender = Gender.objects.all() categories = Category.objects.all() colors = Color.objects.all() materials = Material.objects.all() query = request.GET.get('query','') products = Product.objects.all().order_by('-pk') if query: products = products.filter( Q(name__icontains=query)| Q(sub_name__icontains=query) ).distinct() paginator = Paginator(products, 8) page = request.GET.get('page') cards.html {% load static %} {% block content %} <body> {% for product in products %} <div class="product-card"> <a href="{% url 'productpage' product.slug %}"><div class="main-images"> <img id="black" class="black active" loading="lazy" src="{{product.imageURL}}" alt="blue"> </div></a> <div class="shoe-details"> <span class="shoe_name"> <a href="{% url 'productpage' product.slug %}"><p style="display: -webkit-box;-webkit-line-clamp: 1;-webkit-box-orient: vertical;font-size: 16px; font-weight: 500; color: #161616;width: 100%;overflow: hidden;/* white-space: nowrap; */text-overflow: ellipsis;">{{product.name}}</p></a> </span> </div> <div class="price"> <span class="price_num">{{product.price|floatformat:2}}TL</span> </div> </div> {% if product.stock > 0 %} … -
Django View Not Being Called from Template Form
This is my first time using Django (and I'm a beginner in web development in general), so I'm making a very simple project. It's a "daily check-in" app, where every day I click a button to check in, and I can view the history to see days I checked in or missed. The page is very minimal right now: My problem is I can't get the buttons to connect to their functions. Following along the official documentation, my current understanding is that the Django way to handle input is to wrap elements in a <form> that POSTs to a view, which is mapped in urls.py. Snippet of home.html: <div id="buttons-container"> <form action="{% url 'checkin-checkin' %}" method="post" style="display: inline;"> {% csrf_token %} <input type="button" value="Check in"> </form> <form action="{% url 'checkin-history' %}" method="post" style="display: inline;"> {% csrf_token %} <input type="button" value="View history"> </form> </div> Snippet of views.py: def home(request: HttpRequest) -> HttpResponse: # query DB to see if user is checked in... checked_in = True # hard-coded for now return render(request, "checkin/home.html", context={ "title": "Daily Check-in", "checked_in": checked_in, }) def checkin(request: HttpRequest) -> HttpResponse: print("called checkin") return home(request) # temp, just to return something def history(request: HttpRequest) -> HttpResponse: print("called history") …