Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get the top 3 elements of a Django nested query
Using django with a MySQL DB and given these models: class Post(models.Model): title = models.CharField(max_length=255, db_index=True) . . . author = models.ForeignKey('Account', on_delete=models.SET_NULL, null=True ) tags = models.ManyToManyField('Tag', blank=True) reactions = models.ManyToManyField('Reaction', through="PostReaction", related_name='reactions', blank=True) class Account(AbstractUser): slug = models.SlugField(max_length=150, db_index=True, blank=True, null=True) avatar = models.URLField(default='', blank=True) class PostReaction(models.Model): reaction = models.ForeignKey('Reaction', on_delete=models.CASCADE, ) post = models.ForeignKey('Post', on_delete=models.CASCADE,) reacted_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey('Account', on_delete=models.CASCADE, ) class Reaction(models.Model): reaction_name = models.CharField(max_length=250, unique=True) reaction_url = models.CharField(max_length=2048) reaction_category = models.ForeignKey('ReactionCategory', on_delete=models.CASCADE) View for a list of published posts : class PostListView(generics.ListAPIView): queryset= Post.objects.filter(is_publish = True).select_related('author').prefetch_related('tags','reactions') serializer_class = PostListReadSerializer Serialisers to produce a JSON list of posts: class TagListSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = '__all__' class PostShortReactionSerializer(serializers.ModelSerializer): class Meta: model = Reaction fields = ["reaction_name", "reaction_url", "id"] class PostAccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ["username", "avatar"] class PostListReadSerializer(serializers.ModelSerializer): tags = TagListSerializer(many=True, read_only=True) reactions = PostShortReactionSerializer(many=True, read_only=True) author = PostAccountSerializer(read_only=True) class Meta: model = Post fields='__all__' Tried to form a subquery to retrieve the required data, but the query is not executed in the output: Option one: sq= Subquery(PostReaction.objects.filter(post=OuterRef('id')).values_list('id', flat=True)[:3]) subquery = PostReaction.objects.filter(post=68).values('reaction__id').annotate(reaction_count=Count('reaction__id')).order_by('-reaction_count')[:3] queryset = Post.objects.filter(is_publish = True).select_related('author').prefetch_related('tags', Prefetch('reactions', queryset=PostReaction.objects.filter(post=sq))) In the second option, grouping fails (naturally) and outputs rows … -
Default error display in HTML is not working for formset factory in Django
I am new to Django and I'm trying to create Recipe web app. I am trying to make formset factory which create forms for ingredients. User can dynamically add ingredient by clicking button. I would like to ask you how displaying errors in HTML template works. For ingredient name field in Ingredient form if length of string is less than 3 it display automatic error message. Display error if length of string is less than 3 Unfortunately when field is empty the error is displaying in another way: Display error if string is empty Could someone tell me why this default display is working when length is less than 3 but is not working when string is empty? There is my code: Ingredient Form: class IngredientForm(forms.Form): ingredient_name = forms.CharField(max_length=64, required=True, min_length=3, label="Nazwa składniku") amount = forms.FloatField(initial=0, label="Ilość", required=True) unit = forms.ChoiceField(choices=unit_choices, required=True, label="Jednostka") class IngredientFormSet(BaseFormSet): def clean(self): """Checks that every ingredient is non-empty""" if any(self.errors): return for form in self.forms: data = form.cleaned_data if not data: raise ValidationError("Form doesn't have any data") Recipe View: class RecipeAddView(View): ingredient_formset = formset_factory(IngredientForm, formset=IngredientFormSet) recipe_form = RecipeForm() template_name = "add_recipe.html" def get(self, request): context = {"ingredient_formset": self.ingredient_formset(), "recipe_formset": self.recipe_form} return render(request, "add_recipe.html", context) def … -
Offline deployment of python scypy and django
I've got a django/pandas/scipy application. I need to deploy them on a Windows Server 2012 machine without Internet access. So, I can't make a pip install in that machine. Furthermore, to install numpy, scipy and more, some of the libraries need to compile some libraries like openblas and more, so deployment is a nightmare. You need too many things to do for this deployment. Docker is not an option. I've got a VM right now, but I want to get rid of it. Is there any posibility to encapsulate a python - scipy to make a deployment on a machine without making it a real nightmare? -
Problem with connecting Django and Mongoengine
I have a problem with connecting django and mongoengine. I do all things as tutorial describes but it is not working. The problem is in part of commenting DATABASE part in settings.py. How could I resolve it? dependencies: djangorestframework==3.14.0 django-rest-framework-mongoengine==3.4.1 django-cors-headers==3.14.0 pymongo[snappy,gssapi,srv,tls]==4.3.3 mongoengine==0.27.0 dnspython settings.py import mongoengine mongoengine.connect(db="mongo", host="mongodb://localhost:27017") # DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.postgresql_psycopg2', # 'NAME': 'db_name', # 'USER': 'my-name', # 'PASSWORD': 'my-pass', # 'HOST': '127.0.0.1', # 'PORT': '5432', # } # } error: (venv) PS C:\Users\barma\PycharmProjects\spr_django> python manage.py migrate Traceback (most recent call last): File "C:\Users\barma\PycharmProjects\spr_django\manage.py", line 22, in <module> main() File "C:\Users\barma\PycharmProjects\spr_django\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\base.py", line 448, in execute output = self.handle(*args, **options) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\base.py", line 96, in wrapped res = handle_func(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\commands\migrate.py", line 114, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) (venv) PS C:\Users\barma\PycharmProjects\spr_django> python manage.py migrate Traceback (most recent call last): File "C:\Users\barma\PycharmProjects\spr_django\manage.py", line 22, in <module> main() File "C:\Users\barma\PycharmProjects\spr_django\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\barma\PycharmProjects\spr_django\venv\Lib\site-packages\django\core\management\base.py", line … -
Add textearea in forms (Django)
Sorry for bad english, im from Argentina. class Formulario_Contacto(forms.Form): asunto=forms.CharField(label="Nombre", required=True) email=forms.EmailField(label="Email", required=True) mensaje=forms.CharField(label="Contenido", required=True, widget=forms.Textarea) enter image description here Here is my views.py def contacto(request): #Si el metodo de request es POST, pasa esto, eso quiere decir el codigo de abajo if request.method=="POST": miFormulario=Formulario_Contacto(request.POST) if miFormulario.is_valid(): #Si el formulario es valido, hay que crear una variable donde almacenar la info que se ingreso, en este caso la llame formularioFinal formularioFinal=miFormulario.cleaned_data send_mail(formularioFinal["asunto"], formularioFinal["mensaje"], formularioFinal.get("email",""),["julian_regueira@hotmail.com"],) return render (request, "Contacto/gracias.html") else: miFormulario=Formulario_Contacto() return render(request, "Contacto/Form_Contacto.html", {"form":miFormulario}) I want to expand the text area in "mensaje" -
Django: manage.py makemigrations causes this: django.db.utils.OperationalError: no such table
I'm new on Django and I'm learning how to use DBs (SQLite). When I try to create a table gestione_libro inside an app called gestione from a class in models.py with the command python manage.py makemigrations gestione I get this error Traceback (most recent call last): File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: gestione_libro The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/filippobologna/Desktop/Università/TERZO_ANNO/2_semestre/Tecnologie Web/prova/manage.py", line 22, in <module> main() File "/Users/filippobologna/Desktop/Università/TERZO_ANNO/2_semestre/Tecnologie Web/prova/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/management/base.py", line 443, in execute self.check() File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/management/base.py", line 475, in check all_issues = checks.run_checks( File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/checks/registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/checks/urls.py", line 14, in check_url_config return check_resolver(resolver) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/core/checks/urls.py", line 24, in check_resolver return check_method() File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/urls/resolvers.py", line 494, in check for pattern in self.url_patterns: File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/utils/functional.py", line 57, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/urls/resolvers.py", line 715, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/filippobologna/.local/share/virtualenvs/prova-z1eNkf-m/lib/python3.9/site-packages/django/utils/functional.py", … -
How to check if username is already exist in database in django and show the error "username is already taken "in template html page
I'm new in Django and web develoment. So, I have a costum user model looks like this in my models.py class MyAccount(AbstractBaseUser): first_name = models.CharField(max_length=100) middle_name = models.CharField(max_length=100, blank=True) last_name = models.CharField(max_length=100, blank=True) username = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=254, blank=True) club_favorite = models.CharField(max_length=100) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) object = MyAccountManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['first_name', 'middle_name', 'last_name', 'club_favorite', 'email'] def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_admin class MyAccountManager(BaseUserManager): def create_user(self, username, first_name, middle_name, last_name, club_favorite, email, password=None): if not username: raise ValueError("Users must have a username") user = self.model( username = self.normalize_email(username), first_name = first_name, middle_name = middle_name, last_name = last_name, club_favorite = club_favorite, email = email, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, first_name, middle_name, last_name, club_favorite, email, password=None): user = self.create_user( username, password = password, first_name = first_name, middle_name = middle_name, last_name = last_name, club_favorite = club_favorite, email = email, ) user.is_admin = True user.save(using=self._db) return user from views.py def register(request): if request.method == 'POST': if(request.method == "POST"): first_name = request.POST.get('first_name') middle_name = request.POST.get('middle_name') last_name = request.POST.get('last_name') username = request.POST.get('username') password1 = request.POST.get('password1') password2 = request.POST.get('password2') email = request.POST.get('email') club_favorite … -
password reset in Django
can you please help. So I did a password reset on the site but could not find on the Internet how to change this data to my own. Thanks in advance type here ---enter image description here Please help solve this problem. -
Django Reverse Not Found, upgrade from 2.0 to 3.2
Template: {% url 'activate' uidb64=uid token=token %} Views: def email_activate(user, generated_token): message = render_to_string('e_activate.html', { 'user': user, 'domain': settings.DOMAIN, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': generated_token, 'base_domain': settings.DOMAIN, }) #etc... def activate(request, uidb64, token): uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) #etc... Urls: re_path(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$', views.activate, name='activate') Previously I was using Django 2.0 and this method worked fine. Now I have upgraded to 3.2 and its causing errors. The first error I got is related to urlsafe_base64_encode(force_bytes(user.pk)).decode() which I have changed to urlsafe_base64_encode(force_bytes(user.pk)) as its already returning string (Django 3.2) instead of bytes (Django 2.0) The current ongoing issue: Error during template rendering In template /path/etc Reverse for 'activate' with keyword arguments '{'uid64': 'etc', 'token': 'etc'}' not found. 1 pattern(s) tried: ['computerapp\\/activate/(?P<uid64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] Any thoughts as to why this is happening since upgrading to 3.2? I did have a look at Django 3.2 Docs.. -
Static files not found error deploy django nginx gunicorn ubuntu 18.04
I'm a python Django developer and I'm facing a problem in my deploy. THE SERVER IS WORKING NORMALLY, BUT IT DOES NOT FIND AND DOES NOT RECOGNIZE THE STATIC FILES. I'm using an ubuntu 18.04 server. I made all the necessary configurations: I created the file gunicorn.socket and the gunicorn.service and they are already working normally. The next step was to create the server{}. At the moment, I haven't applied https and security, I just want to access the server by the same ip, in an http way. My file is like this: server { listen 80; server_name localhost; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /root/myproject; } location /media { alias /root/myproject/media/; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } The user is: root The root path of my project is this: /root/myproject -> It doesn't have the /home folder like it usually does. I already checked it STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'templates/static' ] STATIC_ROOT = BASE_DIR / 'static' Regarding the settings in settings.py, I already put the STATIC_ROOT and I already made the python manage.py collectstatic Another detail: I put the {% static load %} and … -
django-rest-framework web interface is showing datetime in this format DD-MM-YY --:-- --
When I send a post request from drf web interface I am getting this error - "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm:ss.uuuuuu[+HHMM|-HHMM]." I have tried all the resources on the internet, but none of them worked for me. So, I am posting here, and if anyone can help, it will be appreciated. Thank you in advance **- This is what I am doing - ** [models.py] from django.db import models from UserAuthenticator.models import User # Create your models here. class UserInsuranceModel(models.Model): customer_name = models.ForeignKey(User, on_delete=models.CASCADE, null=True) insurance_id = models.CharField(max_length=100, unique=True) vehicle_number = models.CharField(max_length=100, unique=True) rc_front = models.ImageField(upload_to="media", null=False, blank=False) rc_back = models.ImageField(upload_to="media", null=True, blank=True) nominee_name = models.CharField(max_length=100) nominee_dob = models.DateField(null=True, blank=True) insurance_created_at = models.DateTimeField(auto_created=True) insurance_started_at = models.DateTimeField(null=True) insurance_valid_till = models.DateTimeField(null=True) is_insurance_verified = models.BooleanField(default=False) is_insurance_cancelled = models.BooleanField(default=False) def __str__(self): return str(self.customer_name)` [serializer.py] from rest_framework import serializers from .models import UserInsuranceModel from UserAuthenticator.models import User class UserInsuranceSerializer(serializers.ModelSerializer): insurance_started_at = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S.%fZ") insurance_valid_till = serializers.DateTimeField(format="%Y-%m-%dT%H:%M:%S.%fZ") class Meta: model = UserInsuranceModel fields = ('customer_name', 'insurance_id', 'vehicle_number', 'rc_front', 'rc_back', 'nominee_name', 'nominee_dob', 'insurance_created_at', 'insurance_started_at', 'insurance_valid_till' 'is_insurance_verified', 'is_insurance_cancelled')` [views.py] from rest_framework import generics, status from .models import UserInsuranceModel from .serializer import UserInsuranceSerializer from rest_framework.views import Response class UserInsuranceApiView(generics.CreateAPIView): queryset = UserInsuranceModel.objects.all() serializer_class = … -
django-how to upload main folder and subfolder,subdirectory,subfiles using forms.py and store data main foldername in models.py
I do select folder but select all subfiles only and include subfolder files are select. Example: I select one folder but folder inside 16 files is there, that files are stored in one bye one in database and storage area this is my probelm. Try: views.py def upload_folder(request): if request.method == 'POST': form = FormFiles(request.POST, request.FILES) if form.is_valid(): files = request.FILES.getlist('file') for file in files: myfile = FolderModel(file=file) myfile.save() return HttpResponse("success") else: form = FormFiles() return render(request, 'folderupload.html', {'form': form}) forms.py class FormFiles(forms.Form): folder = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True, 'webkitdirectory': True})) class Meta: model = FolderModel fields = ['file'] Expected: I store main folder name on database. Then how to i expect of my Media storage how to upload Tree format same format stored in. -
json_script and concatenate variable name
I need to concatenate the variable name from a template variable and hand it to the json_script template tag. I tried: {% with sensorname|add:"-data" as SensorNameData %} {{ values|json_script:SensorNameData }} output: {{ SensorNameData }} {% endwith %} Which did not work, so I created a filter templatetag: @register.filter def combined(str1, str2): return f"""{str1}{str2}""" and tried: {{ values|json_script:sensorname|combined:"-data" }} but when applying it, I end up with the parsed list of values and then -data. Can I somehow tell the template processor to validate sensorname first and then values|json_script:xxx? -
after change language stay same page in django?
I try this way: <a class="dropdown-item" href="/{{ language.code }}/{{ request.get_full_path|slice:"4:" }}">{{ language.name_local }} and it work but in some page it don't work for example: I have a url like this http://127.0.0.1:8000/products/ but after changing language it will like this: http://127.0.0.1:8000/en/ducts/ but if I enter url like this http://127.0.0.1:8000/fa/products/ then change language it's fine. and url it's correct: http://127.0.0.1:8000/en/products/ I wanna after changing language stay same page -
Django project - JS not loading after moving it out of HTML to own file in static folder
Here is my folder organization When i had the JS directly in the HTML file, everything worked as expected. Since I moved it to a spots.js file, it doesn't load or appear in the network tab, but i can reach it by going to file location in the server. I am in Debug mode. In my settings.py I have: STATIC_URL = '/users/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'var', 'static') In my urls.py, I have: urlpatterns = [ path('', home, name='users-home'), path('register/', RegisterView.as_view(), name='users-register'), path('profile/', profile, name='users-profile'), path('select-spots/', select_spots, name='select-spots'), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) In my views.py I have: @login_required def select_spots(request): spots = [] with open('spotscsv.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: spots.append({ 'name': row['name'], 'latitude': float(row['latitude']), 'longitude': float(row['longitude']), }) return render(request, 'users/select_spots.html', {'spots': spots}) And in my select_spots.html, I have: {% extends 'users/base.html' %} {% load static %} <script src="{% static 'myapp/spots.js' %}"></script> I have tried so many different variations but it still doesn't load on page. Do you know why not? I tried changing the spots location, i tried collecting static, I tried different code. -
Python - Creating two models with 1-1 relationship in a same model.py file (hierarchy problem) in Django
Hey I'm facing this problem when I want to create 1:1 relationship IDK if I'm missing something here or what am I doing wrong here in one app.model.py I'm trying to create 2 models like below : class Manager(models.Model): user_id = models.ForeignKey('BeautySalon.Salon',on_delete=models.DO_NOTHING) #FK businessL_id = models.BooleanField(default = False, blank = False) salon_id = models.ForeignKey(Salon,on_delete=models.DO_NOTHING) #FK class Salon(models.Model): # name, manager_id--Manager, city_id--City, address, tell, description, starting hour , closing hour, PTG, rank--Rank name = models.CharField(max_length=200) manager = models.ForeignKey(Manager,on_delete=models.DO_NOTHING) # FK city = models.ForeignKey(City,on_delete=models.DO_NOTHING) #FK address = models.TextField(null = False, max_length = 1000) tell = models.CharField(max_length=24) description = models.TextField(null= False, max_length = 1000) strHour = models.TimeField() clsHour = models.TimeField() PTG = models.BooleanField(default = False, blank = False) rank = models.ForeignKey(Rank,on_delete=models.DO_NOTHING) #FK but when I try to make migrations I get this error Field defines a relation with model 'Salon', which is either not installed, or is abstract. In C++ I would face the same problem but we could call the name at the top to let it know, IDK how to do it in python I've tried this : class Salon (models.Model): pass but it didn't work I appreciate your help -
Using class-based views save a form with 2 related models (via foreign key)
WANT TO DO using CreateView I launch an hmtm page containing a form. This page has had two embedded forms sent in like {{address}} and {{ship}}. The ship model has a foreign key linking it to the address table address_id. I can do this easily using function-based views, but I want to do it via class-based. I create my models, then I do something like this in the view that launches the html page: context = { 'address_form': AddressForm(), 'ship_form': ShipForm(), ) } return render(request, 'app/registration.html', context) The html looks sommething like this: ` {{ address_form }} {{ ship_form }} <input type="submit" value="Register"> ` When I click on submit, the form does connect to the database BUT it tries to save the ship form but it fails because it doesn´t have the address_id and of course, the reason is that the address_form could not be saved first, and this is what is blocking my progress. I know I can do ´some´ manipulation inside the CreateView that launched the html page, like in here def form_valid(self, form): # This method is called when valid form data has been POSTed. but there is no way I can reach the address form, it … -
Django approach for simple app structure?
I'm back to coding after almost 20 years working as a manager. Decided to play with python as I like the language started with some simple desktop apps and now I want use django and do some web development. I'm creating a series of small apps to help me with daily stuff at the company (time management, reading logs, creating slides based on those logs etc. Now question is: Django has a "front end" section and an "Admin" section. If I'm creating that kind of apps what approach should I go for? Develop everything in the Admin area or do that in the front area and save the admin if I need to create some configurations and stuff? I will use authentication for it in case this can be a issue. No access if you dont have an user and password that will be created by me. No self registering Guidance how to add an app to django the best way to suit my needs without loosing the power of the framework -
how to get the value from drop down and send it to the view.py method
Filter By Year Select Year . this is the code of drop down. i want that the selected one should be send to the views. so i wrote this script code. // Get the current year const currentYear = new Date().getFullYear(); // Set the maximum number of years to display in the dropdown menu const maxYears = 50; // Get the year menu element const yearMenu = document.getElementById("year-menu"); // Set the height of the year menu and add a scrollbar yearMenu.style.maxHeight = "200px"; yearMenu.style.overflowY = "scroll"; // Generate the years dynamically from 1950 to the current year, up to the maximum number of years for (let year = currentYear; year >= 1950 && year > currentYear - maxYears; year--) { // Create a new year item const yearItem = document.createElement("li"); // Create a new year link const yearLink = document.createElement("a"); yearLink.setAttribute("href", "#"); yearLink.textContent = year; // Add an event listener to update the year button when a year is clicked yearLink.addEventListener("click", function() { document.getElementById("year-button").textContent = year; }); // Add the year link to the year item yearItem.appendChild(yearLink); // Add the year item to the year menu yearMenu.appendChild(yearItem); } </script> but if i submit the form. It is throwing the error … -
Celery dockerfile
I'm using Django and celery together in an app(or container) but I want to separate celery in another app(or container). I am not sure how should I do this because my tasks are in the Django app. so how should I set celery parameters in order to access tasks? -
How do I pass kwargs to url when posting data? I keep getting: No ReserveMatch Error
I have spent all day trying but cannot workout what I am doing wrong. I have two views, one loading the main view and one calling a modal to send an email. When I post data through the modal I get a reverse match error and not sure why. Funny enough if I empty a field in the modal it get no error as the pk is there. Please tell me what I am doing wrong. I understand that someone I am not passing the pk back to the template ones data are posted, but how do you do that? Using get_form_kwargs did not work. Error: Reverse for 'application-update' with keyword arguments '{'pk': None}' not found. 1 pattern(s) tried: ['update/(?P[0-9]+)/$'] Template {% url 'application-update' pk=application_update.id %} {% url 'send-message' %} urls.py re_path(r'^update/(?P<pk>[0-9]+)/$', views.ApplicationViewUpdate.as_view(), name="application-update") re_path(r'^send/$', views.SendMesssageView.as_view(), name="send-message"), ] views.py class ApplicationViewUpdate(UpdateView): model = Application form_class = ApplicationForm template_name = 'update_application.html' context_object_name = 'application_update' success_url = '/update/{id}/' def get_context_data(self, *args, **kwargs): context = super(ApplicationViewUpdate, self).get_context_data(*args, **kwargs) context['id'] = self.kwargs['pk'] application = Application.objects.get(id = context['id']) context['message'] = MessageForm() return context class SendMesssageView(FormView): form_class = MessageForm template_name = 'message.html' context_object_name = 'send_message' success_url = '/send/' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) … -
How to position Django help_text between Label & Input instead of under Input?
I have a custom form where each field is added as a widget, i.e. widgets = { "title": forms.TextInput( attrs={"class": "review-input review-title"}, ), } I also added help_texts in the Meta class of this form i.e. help_texts = { "title": "Help text title", } By default, this puts the help text below the input tag. enter image description here However, I want to place the help text between label & input. The form is generated as {{ form.as_p }} inside a flex-box. Could you please help with that? I already tried to style the generated help text, but it messed the whole form/layout. It would help to have it generated in the right place from the start. -
AttributeError: type object 'Product' has no attribute 'object'
`models.py from django.db import models from django.contrib.auth.models import User class Product(models.Model): title = models.CharField(max_length=100) selling_price = models.FloatField() discounted_price = models.FloatField() description = models.TextField() composition = models.TextField(default='') prodapp = models.TextField(default= '') #brand = models.CharField(max_length=100) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) product_image=models.ImageField(upload_to="product") def str(self): return self.title views.py from django.views import View from . models import Product, Cart, Customer def add_to_cart(request): user=request.user product_id=request.GET.get('prod_id') product = Product.object.get(id=product_id) Cart(user=user,product=product).save() return redirect("/cart")` ''' my error: File "C:\Users\SIRI\OneDrive\Desktop\E-com\ec\app\views.py", line 107, in add_to_cart product = Product.object.get(id=product_id) ^^^^^^^^^^^^^^ AttributeError: type object 'Product' has no attribute 'object' [29/Apr/2023 13:08:43] "GET /add-to-cart/?prod_id= HTTP/1.1" 500 67990 ''' I am learner i don't where i did mistake can you please fix it DM me by mail eaglemem78@gmail.com ` -
App is crashed while deploying django app on railway
while deploying my django app it always run collectstatic and asking yes or no. Adding whitenoise didn't solve it . -
The last_run_at time is inconsistent with my current time
Summary: Include a brief description of the problem here, and fill out the version info below. Celery Version: 5.2.7 Celery-Beat Version:2.3.0 Django 4.0.7 Exact steps to reproduce the issue: django settings.py DJANGO_CELERY_BEAT_TZ_AWARE = False TIME_ZONE = 'Asia/Shanghai' USE_TZ = False celery app.conf.timezone = 'Asia/Shanghai' app.conf.enable_utc = False CrontabSchedule 'timezone': app.conf.timezone Detailed information I set the expires property of the task, but the task does not stop executing when it expires. I checked the task data and found that the last_run_at is 8 hours ahead of the current time. I think it might be a time zone issue,but both django and celery I set timezone='Asia/Shanghai' and set enable_utc=False. Can anyone tell me how to solve this problem The last_run_at time is consistent with my current time