Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - I need the total sum displayed after a filtered search
I am hoping to get an answer to what I believe is probably a simple solution, but my current Python/Django knowledge is limited, and I cannot seem find anything when I Google it. I have column in a table that has decimal values and linked to that table is a filter which is searching by date and site code. I want the total sum of the column to be displayed after I perform the search. I have an aggregation setup on that column, which is working but it is not dynamic and when I perform a search it just keeps the value of the total to be the unfiltered result. The desired response would be for the total to change with each search result. Models.py class expense(models.Model): ExcludeTax = models.DecimalField('Exclude Tax', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) IncludeTax = models.DecimalField('Include Tax', max_length=20, blank=True, null=True, max_digits=10, decimal_places=2) user = models.ManyToManyField(dbmobile, blank=True) Date = models.DateField(default=now) Views.py def expense_table(request): item = expense.objects.all().order_by('IncludeTax') add = expense.objects.all().aggregate(Sum('IncludeTax'))['IncludeTax__sum'] search_list = expense.objects.all().order_by('user__Site_Code', 'Date') search_filter = expenseFilter(request.GET, queryset=search_list) return render(request, 'expense/MExpense.html', {'item': item, 'filter': search_filter, 'add': add}) filters.py class expenseFilter(django_filters.FilterSet): Date = django_filters.DateFromToRangeFilter(widget=RangeWidget(attrs={'type': 'date'})) class Meta: model = expense fields = ['Date', 'user__Site_Code'] html <tfoot> <tr> <td><b>Total</b></td> <td><b>{{add}}</b></td> </tfoot> -
Dockerfile commands not running on compose but working in the CLI after the container is built
I'm currently learning docker and trying to deploy my django project to a local container with postgres and redis. When I run docker compose the container builds and lets me connect to the django server but it is missing some of the pip requirements and libraries specified in the Dockerfile. If I run the commands from the Dockerfile in the CLI of the container they all work correctly. The Dockerfile used in the docker compose, gcc library installs correctly but g++ and any of the other unixodbc libraries don't exist in the container when checking from the CLI interface. Here is the docker compose file, version: '3.8' services: dashboard-server: build: context: ./ command: python manage.py runserver 0.0.0.0:8000 container_name: dashboard-server depends_on: - dashboard-redis - dashboard-database environment: - PGDATABASE=django - PGUSER=django - PGPASSWORD=2bi3f23f2938f2gdq - PGHOST=dashboard-database - PGPORT=5432 - REDIS_URL=redis://dashboard-redis:6379/0 ports: - "80:8000" volumes: - ./:/usr/src/app dashboard-redis: container_name: dashboard-redis image: redis:6-alpine dashboard-database: container_name: dashboard-database image: postgres:13-alpine environment: - POSTGRES_USER=django - POSTGRES_PASSWORD=2bi3f23f2938f2gdq ports: - "5433:5432" expose: - 5432 volumes: - dashboard-database:/var/lib/postgresql/data volumes: dashboard-database: The Dockerfile in the same directory, # pull official base image FROM python:3.8 # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install … -
Django Manager and QuerySets: How may I set up my manager and query to retrieve Parent ForeignKey ID in models.Queryset to build a folder directory?
How can I extract Parent ForeignKey IDs of ManyToManyFields by a Manager to build a path that i may a build Folder Directory? I can query in the shell to retrieve the parent ID. Output is Board.id = 1 which is correct In [37]: _id = Column.objects.all() In [38]: _id[0].board.id Out[38]: 1 if i try to reproduce in Manager i return with error TypeError: 'ForeignKeyDeferredAttribute' object is not callable So as soon as a board is initiated a folder is created as you can see in the Board Model. Now i have a child model called Column that has a ForeignKey field from Board. Objective is create child sub-folder in the directory as soon as Column model saves. So the model needs to lookup the parent ID and add Column.id to a relative path Therefore i believe logically i should query the Foreign key in the Column model and build a relative path as described in ColumnQuerySet. In short, how can i create a subdirectory folder? Any Ideas? Thank you for any help. Model.py class Board(models.Model): name = models.CharField(max_length=50) owner = models.ForeignKey( User, on_delete=models.PROTECT, related_name="owned_boards" ) members = models.ManyToManyField(User, related_name="boards") class Meta: ordering = ["id"] def __str__(self): return self.name def … -
Django Templates - Best Practice in Avoiding Repeating Code that Require Different For Loops?
I'm creating a blog and have numerous pages that will display a list of articles. So, to avoid repeating that code, I'm trying to place it within a parent template that I can extend where needed. The problem is I'll need a different for loop to display the article lists on each page/view. I figure the easiest approach would be to simply create blocks where I want the loop to start and close within the parent, then alter accordingly within each child. However, Django doesn't allow you to close blocks that have an open for loop, despite closing the loop later in a different block. My initial approach, in the parent, article_list.html: <div class="row"> {% block loop_start %} {% endblock loop_start %} <div class="col-xs-12 col-sm-4"> <div class="card"> <a class="img-card"> <img class="img-fluid"src="../../static/{{ post.featured_image }}" /> </a>.... etc I know I have to fix my src code. Extends to child as: {% block loop_start %} {% for post in recent_articles %} {% endblock loop_start %} However, that doesn't work as noted above. I've also tried wrapping the entire code for the article list in a block, extending it and performing the following within the child: {% for post in recent_articles %} {% … -
Is there a way I can extend Django login_required decorator to check for a boolean field in my custom model?
I am working on a web application that has 5 different kinds of users, which are being differentiated by boolean fields in my custom user model. is_estate_vendor = models.BooleanField( _('estate_vendor'), null=True, blank=True, help_text=_( 'Designates whether this user should be treated as an estate admin.' ), ) is_estate_admin = models.BooleanField( _('estate_admin'), null=True, blank=True, help_text=_( 'Designates whether this user should be treated as an estate admin.' ), ) is_estate_security = models.BooleanField( _('estate_security'), null=True, blank=True, help_text=_( 'Designates whether this user should be treated as estate security.' ), ) is_estate_residence = models.BooleanField( _('estate_residence'), null=True, blank=True, help_text=_('Designates whether this user should be treated as estate residence.' ), ) is_estate_head_security = models.BooleanField( _('estate_head_security'), null=True, blank=True, help_text=_( 'Designates whether this user should be treated as estate head security.' ), ) is_super_admin = models.BooleanField( _('super_admin'), null=True, blank=True, help_text=_( 'Designates whether this user should be treated as superadmin.' ), ) I'm trying to extend Django login_decorator to check for which user is logged-in base on which of that boolean fields is true and redirect any authenticated user to the login page if he/she tries to access the dashboard of another kind of user. I tried to create a custom decorator that checks for those fields: def vendor_login_required(function): def wrapper(request, … -
no such column: dashboard_book.id django
I am trying to save data from a pandas DataFrame into the SQLite database on a django project but I keep getting the error "no such column: dashboard_book.id". At the moment I have just a simple Excel file with one column "title" with a string inside. I want to import this into a DataFrame and then save it into Django model. It might seem a bit overkill but it is just the start as I want to build onto it with some automation scripts I have in place. Simple model in models.py: class Book(models.Model): title = models.CharField(max_length=500) Admin registration in admin.py: @admin.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ['title'] Then the attempt to save it into database using dataframe.to_sql() this call is in a separate file with other business logic: data_table = pd.read_excel(setting.import_directory + "/book_table.xlsx") data_table_dataframe = pd.DataFrame(data_table,) engine = create_engine('sqlite://db.sqlite3') data_table_dataframe.to_sql("book", con=engine, if_exists='replace', index=True) When trying to access the model on the admin panel the error is received and no data is being saved into the model. I have tried all different parameters in the to_sql() call and checked the files to make sure I am not missing anything but I cant find where the issue is coming from. Thanks in … -
Updating data on linked models
Here's my user model, class User(AbstractBaseUser, PermissionsMixin, Base): user_id = models.AutoField(primary_key=True) email = models.EmailField(db_index=True, max_length=100, unique=True) is_advisor = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=False) And here's the user profile class UserProfile(Base): profile_id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile') first_name = models.CharField(null=True, blank=True, max_length=100) last_name = models.CharField(null=True, blank=True, max_length=100) thumbnail = models.ImageField() Here's the routers, router.register(r'user', UserViewSet), router.register(r'user/profile', UserProfileViewSet, basename='UserProfile') How do I update the Profile for a specific user, say user_id 3. I'm new to django. -
Django smtp sendmail not working after deployment
I created a contact form for my django app that sends straight to my email after the user completes it. It is working when I run it on my local host but after deployment it take me to an error server error (500) ////settings.py//// import os env = environ.Env() environ.Env.read_env() ** NOTE I ALSO TRIED THIS WITH THE ACTUAL EMAILS INSTEAD OF ENV VARIABLES ** EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = env('EMAIL_HOST') EMAIL_HOST_USER = env('EMAIL_HOST_USER') EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD') EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_USE_SSL = False ///// views.py //// def contact(request): if request.method == "POST": name = request.POST.get('full-name'). email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') data = { "name": name, "email": email, "subject": subject, "message": message, } message = ''' New message: {} From: {} '''.format(data['message'], data['email']) send_mail(data["subject"], message, '', ['svalaiemusic@gmail.com']) return render(request, "contact.html", {}) -
How to secure passwords and secret keys in Django settings file
A django settings file includes sensitive information such as the secret_key, password for database access etc which is unsafe to keep hard-coded in the setting file. I have come across various suggestions as to how this information can be stored in a more secure way including putting it into environment variables or separate configuration files. The bottom line seems to be that this protects the keys from version control (in addition to added convenience when using in different environments) but that in a compromised system this information can still be accessed by a hacker. Is there any extra benefit from a security perspective if sensitive settings are kept in a data vault / password manager and then retrieved at run-time when settings are loaded? For example, to include in the settings.py file (when using pass): import subprocess SECRET_KEY=subprocess.check_output("pass SECRET_KEY", shell=True).strip().decode("utf-8") This spawns a new shell process and returns output to Django. Is this more secure than setting through environment variables? -
Django Submit form with sweetalerts success
I am trying to show an success alert while submitting a form. here is my code. HTML form <button type="submit" class="btn btn-primary" id="successAlert">Add User</button> and the script in the button here. <script> const swalWithBootstrapButtons = Swal.mixin({ customClass: { confirmButton: 'btn btn-primary', cancelButton: 'btn btn-gray' }, buttonsStyling: false }); document.getElementById('successAlert').addEventListener('click', function () { swalWithBootstrapButtons.fire({ icon: 'success', title: 'Success alert', text: 'Your work has been saved', showConfirmButton: true, timer: 4000 }) }); </script> It worked with the type="button", but on the other hand type="submit" does not. -
AttributeError: type object 'PostPagesTests' has no attribute 'post'
I am writing tests for me view.py but getting the type object has no attribute post. Please guys, could you help me out because I have just begun to study python and honestly, have no idea how to fix it. here is my test_views.py from django.contrib.auth import get_user_model from django.test import Client, TestCase from django.urls import reverse from django import forms from posts.models import Post, Group User = get_user_model() class PostPagesTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.user = User.objects.create_user(username='auth') cls.group = Group.objects.create( title='Тестовая группа', slug='test-slug', description='Тестовая группа', ) cls.post = Post.objects.create( text='Тестовый пост', author=cls.user, post_id=cls.post.pk ) def setUp(self): self.user = User.objects.create_user(username='Yes') self.authorized_client = Client() self.authorized_client.force_login(self.user) def test_pages_uses_correct_template(self): tempplates_pages_names = { 'posts/index.html': reverse('posts:index'), 'posts/group_list.html': reverse( 'posts:group_posts', kwargs={'slug': 'test-slug'} ), 'posts/profile.html': reverse( 'posts:profile', kwargs={'username': 'Yes'} ), 'posts/post_detail.html': reverse( 'posts:post_detail', kwargs={'post_id': self.post.pk} ), 'posts/create_post.html': reverse( 'posts:post_edit', kwargs={'post_id': self.post.pk} ), 'possts/create_post.html': reverse('posts:create_post'), } for template, reverse_name in tempplates_pages_names.items(): with self.subTest(reverse_name=reverse_name): response = self.authorized_client.get(reverse_name) self.assertTemplateUsed(response, template) -
How to use decimal quantity for Django-Shop CartItems
Hi I'm trying to edit the demo of Django-Shop. I installed the version 1.2.4 of Django-Shop and Django 3.0.14 In my case I want to sell Products also by wight. As said in the documentation I have to rewrite the CartItem. from django.db import models from django.utils.translation import ugettext_lazy as _ from shop.models import cart class CartItem(cart.BaseCartItem): quantity = models.DecimalField(_("Cart item quantity"), decimal_places=3, max_digits=3) I imported this CartItem in my models.py. After that I had to rewrite the quantity in the class OrderItem aswell class OrderItem(BaseOrderItem): quantity = models.DecimalField(_("Ordered quantity"), decimal_places=3, max_digits=3) # quantity = models.PositiveIntegerField(_("Ordered quantity")) canceled = models.BooleanField(_("Item canceled "), default=False) def populate_from_cart_item(self, cart_item, request): super().populate_from_cart_item(cart_item, request) # the product's unit_price must be fetched from the product's variant try: variant = cart_item.product.get_product_variant( product_code=cart_item.product_code) self._unit_price = Decimal(variant.unit_price) except (KeyError, ObjectDoesNotExist) as e: raise CartItem.DoesNotExist(e) Now I can run the server without problems, but i can't add something to my cart. I looked into the shop.models.cart and tryed by inheriting to overwrite the CartItemManager class class CartItemManager(models.Manager): """ Customized model manager for our CartItem model. """ def get_or_create(self, **kwargs): """ Create a unique cart item. If the same product exists already in the given cart, increase its quantity, if the … -
Django Rest Framework custom readonly field dependant on related model
supposing a models.py like: class User(AbstractUser): pass class Notification(models.Model): value = models.CharField(max_length=255) class NotificationUserLink(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) notification = models.ForeignKey(Notification, on_delete=models.CASCADE) active = models.BooleanField(default=True) The point behind normalizing instead of just having a user field on the Notification itself is for when I want to send the same Notification to hundreds of people I only need 1 Notification object. Suppose I also have an endpoint in views.py like below where the user can see all their notifications and only their notifications, which is achieved by filtering the queryset. class NotificationViewSet(viewsets.ModelViewSet): serializer_class = serializers.NotificationSerializer model = Notification lookup_field='pk' def get_queryset(self): user = self.request.user return Notification.objects.filter(notificationuserlink__user=user) Now the "user" and "notification" pair on the NotificationUserLink model form a candidate key (they are unique together. currently just by business logic but I'll add the actual constraint to the db at some point). Therefore, given a user in the request, each Notification (in the filtered queryset) will have 1 and only 1 NotificationUserLink to that User. Therefore, from the User's perspective, that notification is either active or it isn't, depending on the "active" field on the NotificationUserLink. What I want to accomplish is to include that field ("active") in the serialization of the … -
Django static files are not loading after app deployment on Heroku
from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent #BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-&(o=gy@^4mq_8%b%)7%9-34s45hp^0t0nxa#&l(-x+u50d3(+m' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1','kiranfazaldjango.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'myapp.apps.MyappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / "templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles'), ] MEDIA_URL = … -
Im trying to update the email of a default user in django
I'm trying to update the default user model email with a Model Form and I messed something up in my views. How can I change the email to the input from the form. heres my views @login_required(login_url='home:login') def ChangeEmailView(request): if request.method == 'POST': form = EmailChangingForm(request.POST) if form.is_valid(): emailvalue = User.objects.get(pk=request.user.id) form = EmailChangingForm(instance=emailvalue) return redirect('home:profilesettings') else: form = EmailChangingForm() context = {'form': form} return render(request, 'home/email_settings.html', context) -
Django Rest Framework - Receive Primary Key in POST Response body
I try to build a rest api with Django Restframework. In this Api i use a Model called Event. models.py class Event(models.Model): key = models.IntegerField(auto_created=True, primary_key=True) start_date = models.DateTimeField() end_date = models.DateTimeField() subject = models.TextField(max_length=250) description = models.TextField(max_length=2500) created = models.DateTimeField(default=django.utils.timezone.now) host = models.ForeignKey('auth.User', related_name='host', on_delete=models.CASCADE, null=True) serializers.py class EventSerializer(serializers.HyperlinkedModelSerializer): host = serializers.StringRelatedField() key = serializers.IntegerField(read_only=True) class Meta: model = Event fields = ['url', 'key', 'start_date', 'end_date', 'subject', 'description', 'host'] views.py class EventViewSet(viewsets.ModelViewSet): queryset = Event.objects.all() serializer_class = EventSerializer @action(detail=True) def skills(self, request, *args, **kwargs): return get_key_values(TblClsOne=EventSkills, TblClsTwo=Skills, table_one_column_name="event_id", table_one_fk_name='skill_id', table_two_column_name="skill_id", table_one_filter_value=kwargs["pk"]) def perform_create(self, serializer): serializer.save(host=self.request.user) When I want to see the Details from a event i call GET /events/<id>/ GET /events/502/ Example { "url": "http://127.0.0.1:8000/events/502/", "key": 502, "start_date": "2021-09-23T20:00:00Z", "end_date": "2021-09-23T21:00:00Z", ... "host": null } But if i will create a new Event via POST /events/ i will receive empty fields für keyand url. How can i integrate the created values for this two fields? Theire are mandatory for navigating to the detail view. -
django.db.utils.ProgrammingError: (1146, "Table 'test_x.xxx' doesn't exist")
When I run tests in django app I get this error django.db.utils.ProgrammingError: (1146, "Table 'test_x.xxx' doesn't exist") I tried python manage.py makemigrations and migrate but it doesn't work. Where can be the problem? -
Why won't my django docker container connect to my postgresql container database? Psycopg2 issues?
I just started using django cookiecutter for a project I already made previously. I followed the instructions found here --> https://justdjango.com/blog/django-docker-tutorial to make sure I had the right folders and files to dockerize my project. I'm able to create the containers successfully docker-compose -f local.yml build command prompt log: [+] Building 13.2s (30/30) FINISHED => [tat_local_django internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 1.96kB 0.0s => [tat_production_postgres internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 321B 0.0s => [tat_local_django internal] load .dockerignore 0.0s => => transferring context: 32B 0.0s => [tat_production_postgres internal] load .dockerignore 0.0s => => transferring context: 32B 0.0s => [tat_local_django internal] load metadata for docker.io/library/python:3.9-slim-buster 10.8s => [tat_production_postgres internal] load metadata for docker.io/library/postgres:13.2 10.8s => [auth] library/postgres:pull token for registry-1.docker.io 0.0s => [auth] library/python:pull token for registry-1.docker.io 0.0s => [tat_production_postgres internal] load build context 0.0s => => transferring context: 760B 0.0s => [tat_production_postgres 1/4] FROM docker.io/library/postgres:13.2@sha256:0eee5caa50478ef50b89062903a5b901eb8 0.0s => [tat_local_django internal] load build context 1.1s => => transferring context: 750.89kB 1.1s => CACHED [tat_production_postgres 2/4] COPY ./compose/production/postgres/maintenance /usr/local/bin/maintenanc 0.0s => CACHED [tat_production_postgres 3/4] RUN chmod +x /usr/local/bin/maintenance/* 0.0s => CACHED [tat_production_postgres 4/4] RUN mv /usr/local/bin/maintenance/* /usr/local/bin && rmdir /usr/loc 0.0s => … -
I have the following issue running my django homepage
Using the URLconf defined in naijastreets.urls, Django tried these URL patterns, in this order: admin/ The current path, Quit, didn’t match any of these. -
The 'user_image' attribute has no file associated with it | Djanfo
CODE EXPLANATION In the following code, I had created a user dashboard which is displayed after user creates an account. On dashboard user image is also displayed whether user has uploaded or not. If the user hasn't uploaded the image then a default image is displayed which can be seen below in the code. But it is showing error if user has not uploaded image and works fine if user has uploaded an image. CODE {% if values.user_image.url %} <a class="image" href="{% url 'setting' %}"><img src="{{ values.user_image.url }}" alt=""></a> {% else %} <a class="image" href="{% url 'setting' %}"><img src="{% static 'img/user.png' %}" alt=""></a> {% endif %} ERROR ValueError at /user/setting The 'user_image' attribute has no file associated with it. Request Method: GET Request URL: http://127.0.0.1:8000/user/setting Django Version: 3.2.6 Exception Type: ValueError Exception Value: The 'user_image' attribute has no file associated with it. Exception Location: C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\db\models\fields\files.py, line 40, in _require_file Python Executable: C:\Users\Qasim Iftikhar\anaconda3\python.exe Python Version: 3.8.5 Python Path: ['C:\\xampp\\htdocs\\Projects\\Barter', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\python38.zip', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\DLLs', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib', 'C:\\Users\\Qasim Iftikhar\\anaconda3', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\Pythonwin'] Server time: Sat, 25 Sep 2021 14:38:10 +0000 -
Django Template URL not recognize global value
Starting from a Class based update view (Header table), I call a Class based List View to recover all the details lines created (Lines table) for my Header. It works fine, I can add lines if they don't exist and I can update lines without problems. I have created a GLOBAL val that contains the key value of my Header and here also it works, my List View contains only the lines corresponding to that value. Now I would like to insert a button in the html associated to my List View to return to my Header. The URL works perfectly if hardcode the Header key value but if I try to insert Global variable it doesn't work, it seems that the Global value is empty and obviously I receive errore messages related to a wrong Url. I cannot find the right syntax, I tried a lot of different possibilities without success. Could someone help me? Thanks in advance. Urls.py: urlpatterns = [ path('fttlapphome/', views.fttlapphome, name='fttlapphome'), path('headfttlog/', HeadfttlogListView.as_view(), name='headfttlog_list'), path('headfttlog/add/', HeadfttlogCreateView.as_view(), name='headfttlog_add'), path('headfttlog/<str:pk>/', HeadfttlogUpdateView.as_view(), name='headfttlog_update'), path('deafttlog/', DeafttlogListView.as_view(), name='deafttlog_list'), path('deafttlog/add/', DeafttlogCreateView.as_view(), name='deafttlog_add'), path('deafttlog/<str:pk>/', DeafttlogUpdateView.as_view(), name='deafttlog_update'), path('debfttlog/', DebfttlogListView.as_view(), name='debfttlog_list'), path('debfttlog/add/', DebfttlogCreateView.as_view(), name='debfttlog_add'), path('debfttlog/<str:pk>/', DebfttlogUpdateView.as_view(), name='debfttlog_update'), path('decfttlog/', DecfttlogListView.as_view(), name='decfttlog_list'), path('decfttlog/add/', DecfttlogCreateView.as_view(), name='decfttlog_add'), path('decfttlog/<str:pk>/', … -
Should I create a model to contain another model instances? (Django)
I'm new to django so I'm not sure of the proper way to do things (or the convention). Say I want to make a project which contains my everyday notes. I'm going to create multiple notes every day (where each note is going to be an instance of a "Note" model). I want in my project-frontend to have containers, where I start with containers, each of a specific year (say 2020, 2021, ...) and each of these containers contains month containers (Jan, Feb, ...) and each of those contains day containers (1, 2, ..) and each of those contains the notes of this specific day. Now my question is should, in my backend, make a NoteYear model which has instances of a NoteMonth model which has instances of NoteDay model which has instances of Note model? The reason I thought of this is because it should be faster filtering to get to a specific day. (Of course I'll have a DateTimeField for each Note instance anyways). I'd love to hear your opinions! -
'while', expected 'endblock'. Did you forget to register or load this tag?
I'm working on an ebay like website. On the homepage I would like to render a bootstrap carousel with the most recent postings. I'm using a while loop to cycle through the images I send through to the Django template, but I keep getting this error I think I've properly checked my block tags for typeos, so I'm not sure what would be causing this error. I've also tried moving the endwith tag to after the endwith tag, to no avail. HTML {% extends "auctions/layout.html" %} {% block body %} <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <h2>Active Listings</h2> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> {% with i=0 %} {% endwith %} {% while i < images.count: %} <li data-target="#carouselExampleIndicators" data-slide-to="{{ i }}"></li> {% i+=1 %} {% endwhile %} </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="/static/auctions/images/products.jpeg" alt="First slide"> <div class="carousel-caption d-none d-md-block"> <h5>Check Out What's New</h5> <p>Find these new items below!</p> </div> </div> {% for image in images %} <div class="carousel-item"> <img class="d-block w-100" src="{{ image.url }}" alt="Second slide"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" … -
Django - Cannot access user profile from search query
I am trying to access the profile (OneToOne linked to CustomUser), however, I am not able to. When I try to call {{ user_element.profile.university }} it returns None. But my call request.user.profile.university works just fine. Surprisingly, {{ user_element.first_name }} works fine again. Hence, the issue must be somehow that I am unable to access profile. However, if I type profile wrong (e.g. profile2), it returns "" instead of None. What did I do wrong? models.py: class CustomUser(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile") highschool_or_university = models.CharField(max_length=6, choices=(("school", "Highschool"), ("uni", "University")), blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) university = models.ForeignKey(University, on_delete=models.SET_NULL, null=True) views.py: class SearchResultsView(ListView): model = CustomUser template_name = 'network/search.html' def get_queryset(self): query = self.request.GET.get('q') ret = CustomUser.objects.annotate(full_name=Concat('first_name', V(' '), 'last_name')).filter( full_name__icontains=query) req_email = self.request.user.email ret = ret.exclude(email=req_email) return ret urls.py: urlpatterns = [ path('feed', views.home, name="home"), path('', views.landing, name="landing"), path('about', views.about, name="about"), path('search/', login_required(SearchResultsView.as_view()), name='search'), path('profile_detail/<int:id>/', views.profile_detail, name='profile_detail'), ] search.html: {% extends "base.html" %} {% load static %} {% block title %}Search{% endblock %} {% block content %} <div class="w3-card w3-round w3-white" style="margin: 4px"> <div class="w3-container w3-padding"> <h4>Search Results</h4> </div> {% for user_element in object_list %} <a href="{% … -
Django test OperationalError can't create table
When I'm trying to run my tests in django I get this error django.db.utils.OperationalError: (1005, 'Can\'t create table `test_grocerycheck`.`grocery_check_customuser_groups` (errno: 150 "Foreign key constraint is incorrectly formed")') This table is automatically created by AbstractUser. What should I do in this situation?