Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Fetching information from GET request in dictionary format
I have a html form in which for every option in a select element i can choose multiple values for that option from other select element.For example when i select 'page' then i have 'About','Contact', 'News','Cart' and 'Home' as select options.When i select 'items' then i have 'jeans','pants','hoodies','tshirts' and 'loafers' as options to select. For 'page' i select 'About','Contact' and 'News'.For 'items' i select 'jeans','pants' and 'tshirts'.After selecting these i click on Submit(where name='Save' for input type='submit'). Following is the GET request that i get to see on server side. HTTP GET /testPage/?key_name=page&key_value=About&key_value=Contact&key_value=Home&key_name=items&key_value=jeans&key_value=pants&key_value=tshirts&Save=Submit If i want to fetch information from this request i would do something like this: def myView(request): myKey = request.GET.getlist('key_name',) myKeyValue = request.GET.getlist('key_value',) #I am printing these fetched values just to know how the function works. print(str(myKey)+" , "+str(myKeyValue)) The above print function prints the following: ['page', 'items'] , ['About', 'Contact', 'News', 'jeans', 'pants', 'tshirts'] This printed statement shows that keys- 'page' and 'items' are assigned to myKey variable and values - 'About', 'Contact', 'News', 'jeans', 'pants'and 'tshirts' are assigned to myKeyValue variable. Is there any way that i can fetch information from the GET request in such a way that key values are attached to their β¦ -
OperationalError at /admin/myschoolweb/album/add/ - no such table: main.auth_user__old
I am trying to add new data in table, but every time it gives below error Django Version: 2.1.4 Python Version: 3.7.1 Sqlite3 Version: 2.6.0 I have already gone through all the available answers here, but still the issue persists. I have already followed the steps for 'python manage.py makemigrations' , 'python manage.py migrate'. i tried to upgrade as well as "downgrade your version of sqlite to a version prior to 2.6 (e.g. 2.5.1)", but I don't know how to do this. Can anyone help. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/myschoolweb/album/add/ Django Version: 2.1.4 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myschoolweb'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\db\backends\utils.py" in _execute 85. return self.cursor.execute(sql, params) File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 296. return Database.Cursor.execute(self, query, params) The above exception (no such table: main.auth_user__old) was the direct cause of the following exception: File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\contrib\admin\options.py" in wrapper 604. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\utils\decorators.py" in _wrapped_view 142. response = view_func(request, *args, **kwargs) File "C:\Users\<USER>\Miniconda3\envs\mywebsite\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 44. response β¦ -
How to upgrade Django in visual studio
Is there any method to upgrade the Django and project to the latest version? Thanks, Saeed -
Training and Finetuning a model in AllenNLP
I want to train a model and also finetune it using AllenNLP in a django environment. I want to do these by using the functions(code) available in allennlp github repo. I don't want command line, rather want to pass arguments. How can I do this? Any help will be appreciated. -
From submitted twice
I wanted to upload any file. But when I submit the upload then same post is uploaded twice but in one of it there is no file but just the content and in next there is file. class FileCreateView(PassRequestMixin, SuccessMessageMixin, CreateView): template_name = 'file/upload-file.html' form_class = FileForm success_message = 'File was uploaded successfully' success_url = reverse_lazy('home') def post(self, *args, **kwargs): """ Handle POST requests: instantiate a form instance with the passed POST variables and then check if it's valid. """ # form = self.get_form([self.request.FILES]) form = self.form_class(self.request.POST, self.request.FILES) if self.request.method == 'POST': if form.is_valid(): file = form.save(commit=False) file.upload = form.cleaned_data['upload'] file.author = User.objects.get(pk=self.request.user.pk) file.save() return self.form_valid(form) else: return self.form_invalid(form) home.html <div class="container mt-3"> <div class="row"> <div class="col-12 mb-3"> <button class="upload-file btn btn-primary" type="button" name="button"> <span class="fa fa-plus mr-2"></span>Upload Form</button> </div> </div> {% block extrascripts %} <script type="text/javascript"> $(function () { $(".upload-file").modalForm({formURL: "{% url 'file-upload' %}"}); }); </script> {% endblock extrascripts %} urls.py path('upload/file/', FileCreateView.as_view(), name="file-upload"), model.py class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) visible_to_home = models.ManyToManyField(Home, blank=True) # when none visible to all home visible_to_company = models.ManyToManyField(Company, blank=True) # when none visible to all company # To determine visibility, check if vtc is none or include β¦ -
How to run same project on different port/DNS using Apache2.4 & Windows
I am setting up a UAT and Live environment in a windows server using apache2.4 and mod_wsgi for my Django project. How can I run both projects on different ports/DNS using virtual host configuration? NOTE: I don't have any dedicated DNS that is mapped to the windows server's IP & I'm using the same project in both environments. -
How do I get a value for a non-pk field in a fk?
Good evening, I am relatively knew to Django but I am not understanding how I get a value for a different field referenced by a Foreign Key. For example, I have a model: class Status(models.Model): status_text = models.CharField(max_length=20) status_open = models.BooleanField(default=1) def __str__(self): return self.status_text class Target(models.Model): last_name = models.CharField(max_length=40) first_name = models.CharField(max_length=40) status = models.ForeignKey(Status, on_delete=models.CASCADE) I want to query it: queryset = Target.objects.filter(status__status_open=1) When I do this, I get returned the pk (1,2,3, etc.) for the status field. What I really want is the status_text that corresponds to that pk. I have been playing with select related but it just states that status_text is not a FK. Thanks for your help. I continue to struggle with the ORM in my usage of Django... -
static files django channels
I'have problem in my home page of notifications systeme. I'm follow this course https://arunrocks.com/understanding-django-channels/ this is my js code <script src="{% static '/channels/js/websocketbridge.js' %}" type="text/javascript"></script> <script> document.addEventListener('DOMContentLoaded', function() { const webSocketBridge = new channels.WebSocketBridge(); const nl = document.querySelector("#notifylist"); webSocketBridge.connect('/notifications/'); webSocketBridge.listen(function(action, stream) { console.log("RESPONSE:", action); if(action.event == "New User") { var el = document.createElement("li"); el.innerHTML = `New user <b>${action.username}</b> has joined!`; nl.appendChild(el); } }) document.ws = webSocketBridge; /* for debugging */ }) </script> in console this error is appears -
Django signal not working with django-paypal
I am trying to handle the signal valid_ipn_received from the package django-paypal (docs: https://django-paypal.readthedocs.io/en/stable/standard/ipn.html) engine/signals.py from paypal.standard.models import ST_PP_COMPLETED from paypal.standard.ipn.signals import valid_ipn_received from engine.models import DatasetRequest from django.views.decorators.csrf import csrf_exempt def show_me_the_money(sender, **kwargs): print('test') ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: # WARNING ! # Check that the receiver email is the same we previously # set on the `business` field. (The user could tamper with # that fields on the payment form before it goes to PayPal) if ipn_obj.receiver_email != "paypalemail@gmail.com": # Not a valid payment return # ALSO: for the same reason, you need to check the amount # received, `custom` etc. are all what you expect or what # is allowed. if ipn_obj.mc_gross == ipn_obj.amount and ipn_obj.mc_currency == 'USD': pk = ipn_obj.invoice dsr = DatasetRequest.objects.get(pk=pk) dsr.is_paid = True dsr.save() else: pass valid_ipn_received.connect(show_me_the_money) engine/apps.py from django.apps import AppConfig class EngineConfig(AppConfig): name = 'engine' def ready(self): import engine.signals engine/views.py def pay_for_dataset_request(request, dsr_pk): # dsr_pk = dataset request primary key dsr = DatasetRequest.objects.get(pk=dsr_pk) paypal_dict = { "business": "paypalemail@gmail.com", "amount": dsr.reward, "item_name": dsr.title, "invoice": dsr.pk, "notify_url": request.build_absolute_uri(reverse('paypal-ipn')), "return": request.build_absolute_uri(reverse('datasetrequest_detail', kwargs={'pk': dsr.pk, 'slug': dsr.slug})), "cancel_return": request.build_absolute_uri(reverse('datasetrequest_detail', kwargs={'pk': dsr.pk, 'slug': dsr.slug})), } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = {"form": β¦ -
Django Queryset help, count items associated with item
I am making a web application for an inventory management application using Django. In this web app, storage boxes (with contents) are assigned to people in my database. I am trying to write a queryset that I could loop over (see my HTML) that would retrieve the total number of boxes assigned to each project e.g. Project: Project Green, Total Boxes: 5. Im having difficulty writing this. I've tried to use _Set for a revere lookup and the count function but I can't get anything to work. Could somebody point me int he right direction? I've simplified my code below. My model: class Box(models.Model): box_contents = models.CharField(max_length=300, blank=True, null=True) project_assigned_to = models.ForeignKey('Project', null=True) Location = models.OneToOneField('Location', null=True) class Project(models.Model): project_name = models.CharField(max_length=255, blank=False, null=True) My View: def page(request): project_data = Project.objects.all() return render(request, 'main_app/page.html' , {"project_data":project_data}) My HTML: {% for item in project_data %} <p>Project Name: {{ item.project_name }}</p> <p>Number of Boxes Assigned: {{ item.Box_set.box_contents.count }}</p> {% endfor %} -
Azure Deployment Automation
I'm sure this is a very elementary question... I've built my first Django app and have successfully deployed it to Azure's Web App service. However, after each new deployment, I have to login to the Azure Web SSH and run the following commands to setup the SQL Server connection: apt-get update apt-get install gnupg apt-get install apt-transport-https curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - curl https://packages.microsoft.com/config/debian/9/prod.list > /etc/apt/sources.list.d/mssql-release.list apt-get update ACCEPT_EULA=Y apt-get install msodbcsql17 Once completed, my app runs on Azure as intended. Is there a way to automate these commands so I don't have to manually run them after each deployment? I've read about docker images, but don't know if that's what I need? I'm new to web development, so I apologize in advance if this is a very basic/simple question. Thanks! -
Docker installing wrong django packages
Host Machine: WIndows 10 I created a django project that uses an sqlite database. I tried to put my django app in a container using the following dockerfile: FROM python:3.5 #Enviromental variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 #Work Dir ADD . /code WORKDIR /code # Install dependencies RUN pip install -r requirements.txt Dockercompose file: version: '3.7' services: db: image: postgres:11.1-alpine volumes: - pgdata:/var/lib/postgresql/data/ ports: - 5432:5432 web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db volumes: pgdata: Now, when I try to run the code it gives me this error: Starting iomweb_db_1 ... done Starting iomweb_web_1 ... done Attaching to iomweb_db_1, iomweb_web_1 db_1 | 2018-12-31 20:26:15.535 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2018-12-31 20:26:15.535 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2018-12-31 20:26:15.547 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL. 5432" db_1 | 2018-12-31 20:26:15.576 UTC [19] LOG: database system was interrupted; last known up at 2018 -12-31 19:58:19 UTC db_1 | 2018-12-31 20:26:16.655 UTC [19] LOG: database system was not properly shut down; automatic recovery in progress db_1 | 2018-12-31 20:26:16.662 UTC [19] LOG: redo starts at 0/17ABE00 β¦ -
Having Trouble Getting Started on Heroku with Python
I am setting up a backend for my website with Heroku and Python. By doing so I am following Heroku's setup. But my problem arose at this step here. when I try to run: python manage.py collectstatic I get the following below: Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python2.7/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/Cellar/python@2/2.7.15_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/aaronmiller/Development/python-getting-started/gettingstarted/settings.py", line 14, in <module> import django_heroku File "/usr/local/lib/python2.7/site-packages/django_heroku/__init__.py", line 1, in <module> from .core import * File "/usr/local/lib/python2.7/site-packages/django_heroku/core.py", line 45 def settings(config, *, db_colors=False, databases=True, test_runner=True, staticfiles=True, allowed_hosts=True, logging=True, secret_key=True): ^ SyntaxError: invalid syntax I have tried this 3 times and following the instructions step by step and always get stuck at the part above. With: MacOS 10.14 Python 2.7.15 Python 3.7.2 psql(PostgreSQL) 11.0 pip list dj-database-url 0.5.0 Django 1.11.1 django-heroku 0.3.1 gunicorn 19.9.0 pip 18.1 psycopg2 2.7.6.1 pytz 2018.7 setuptools 40.6.3 whitenoise 4.1.2 heroku pg:info === DATABASE_URL Plan: Hobby-dev Status: Available Connections: 0/20 PG Version: 10.6 Created: β¦ -
Redirect page with Class Based View (CBV) Django 2.1 Python
I want to direct users to a specific page based on their role. I'd like to implement something like this in a class based view. def home_redirect(request): user_role = Profile.objects.get(user = request.user).role if user_role in internal_users: return redirect(reverse_lazy('home')) else: return redirect(reverse_lazy('event_list')) I am aware of RedirectView. But how can I grab the request in a CBV in order to get the user.role as in request.user.role? I know I can get the user.role in certain functions within a CBV by like so: class HomeRedirectView(RedirectView): def get_context_data(self, **kwargs): context = super(HomeRedirectView, self).get_context_data(**kwargs) context['current_user'] = Profile.objects.get(user = self.request.user) user_role = context['current_user'].role return context #Can't access user_role but if I could I would do something like this if user_role in internal_users: url = reverse_lazy('home') else: url = reverse_lazy('event_list') How can I access user_role outside of get_context_data() in a CBV? -
Given an ODBC connection string for a database, how can I modify my settings.py such that my Django app will connect to it?
I have been given an ODBC connection string to connect to a database. However, I am having difficulty in having my Django app to connect to it. What are the proper steps to have my app to connect to it? Am I missing anything in my code? This is my connection string: Driver={SQL Anywhere 17};uid=user;pwd=secret;server=databasename;astart=No;host=127.0.0.1;port=1234 Using a test script that uses pyodbc I am able to connect to the database. However, when I attempt to modify the settings.py file for my app, it fails to connect to the database. Requirements.py django~=2.1.4 pyodbc~=4.0.25 django-pyodbc-azure~=2.1.0.0 Settings.py #First Attempt DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': '127.0.0.1,1234', 'USER': 'user', 'PASSWORD': 'secret', 'NAME': 'databasename', 'PORT': '1234', 'OPTIONS': { 'driver' : 'SQL Anywhere 17', 'host_is_server': 'True', }, } } #Second Attempt DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'HOST': '', 'NAME': 'databasename;', 'PORT': '', 'OPTIONS': { 'host_is_server': 'True', 'dsn': 'Driver={SQL Anywhere 17};uid=user;pwd=secret;server=databasename;astart=No;host=127.0.0.1;port=1234' }, } } For my first attempt, I get the following error: django.db.utils.InterfaceError: ('IM002', '[IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified (0) (SQLDriverConnect)') For my second attempt, I am getting the following error: django.db.utils.Error: ('IM010', '[IM010] [Microsoft][ODBC Driver Manager] Data source name too long (0) β¦ -
Single page design - loading new content on link click
I'm working on a django webpage using single page design approach. Generally what I'm trying to achieve is to have some new content being loaded (picture gallery) to my main webpage after clicking certain links. What I have already achieved is that the new content is being loaded on a link click but unfortunately it seems like the whole page is being reloaded and not rendered correctly. My current implementation is based on having main index.html template and extension template, both using {% block content %} relation. views.py def index(request): categories = Category.objects.all().order_by('name') return render(request, 'index.html', {'categories': categories}) def gallery(request, id): category = Category.objects.get(id=id) return render(request, 'gallery.html', {'category': category}) urls.py urlpatterns = [ path('', views.index, name='index'), path('view_gallery/<int:id>/', views.gallery, name='view_gallery') ] index.html <div class="collapse navbar-collapse" id="collapsibleNavbar"> <ul class="navbar-nav"> {% for category in categories%} <li class="nav-item"> <a class="nav-link" href="{% url 'view_gallery' category.id %}">{{ category.name }}</a> </li> {% endfor %} </ul> </div> <div> {% block content %} {% endblock %} </div> gallery.html {% extends 'index.html' %} {% block content %} <p>{{ category.name }}</p> {% endblock %} I hope I have explained clearly what I'm trying to achieve. Could you please point me in the right direction? -
How can I get static files to work in my Django project?
I'm working through the tutorials in William S. Vincent's Django for Beginners book. I'm in the "Blog App" part of the book, and I've been following his instructions to the letter. However, I cannot seem to get the dev server to serve my static CSS file, no matter what I do. My source code can be found here. I'm using manage.py runserver to run a development demo server for local testing. Here's my directory tree: ./ βββ blog β βββ admin.py β βββ apps.py β βββ __init__.py β βββ migrations β β βββ 0001_initial.py β β βββ __init__.py β βββ models.py β βββ tests.py β βββ urls.py β βββ views.py βββ blog_project β βββ __init__.py β βββ settings.py β βββ urls.py β βββ wsgi.py βββ db.sqlite3 βββ manage.py βββ Pipfile βββ Pipfile.lock βββ static β βββ css β βββ base.css βββ templates βββ base.html βββ home.html Originally I updated my blog_project/settings.py with this line: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] and I put {% load static %} at the top of my templates/base.html file, as well as adding <link href="{% static 'css/base.css' %}" rel="stylesheet"> in the <head> ... </head> section. After writing the static/css/base.css file, this should have worked. But it didn't. β¦ -
Django: page of products (filtered by category) shows nothing
I've a home page that shows the 3 categories we manage: URL: http://127.0.0.1:8000/shop/ In there we've 3 categories: After clicking on any of these, user should be taken to the category page that shows the products related to this category. But right know it does not show any product. models.py class Category(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) image = models.ImageField(upload_to='category', blank=True) class Meta: ordering = ('name',) verbose_name = 'category' verbose_name_plural = 'categories' def get_url(self): return reverse('shop:products_by_category', args=[self.slug]) def __str__(self): return '{}'.format(self.name) class Product(models.Model): name = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) description = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) image = models.ImageField(upload_to='product', blank=True) stock = models.IntegerField() available = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: ordering = ('name',) verbose_name = 'product' verbose_name_plural = 'products' def get_url(self): return reverse('shop:ProdCatDetail', args=[self.category.slug, self.slug]) def __str__(self): return '{}'.format(self.name) shop template: <div class="row col-md-12"> {% for category in categories|slice:":4" %} <div class="col-md-3"> <div class="text-center"> <a href="{% url 'shop:ProdCatDetail' category.slug %}"><img class="my_image_medium" src="{{ category.image.url }}" alt="{{ category.name }}"></a> </div> <p class="text-center">{{ category.name }}</p> </div> {% endfor %} </div> urls.py from django.urls import path from . import views app_name = 'shop' urlpatterns = [ path('', views.allCat, β¦ -
How to allow POST for update action in django rest framework
We're building an API with Django Rest Framework, and our clients want it to have this endpoint: Method: POST URL: api/v1/application/<id> It's basically an update endpoint but with POST instead of PUT. I already have a viewset for this model, and we're using the create, list, and retrieve actions. So, one thing I can do is to allow POST for update actions in Django Rest Framework, but I haven't found how to do that. Also, I can define a custom action like this: @action(methods=['post'], detail=True) def update_status(self, request, pk=None): # some code The problem is this routes to application/<id>/update_status, I can change the route by passing the url_path parameter, but if it's None or empty it just defaults to update_status again. I can also just define this endpoint in a different view and route manually, but that's a worse solution in my opinion, it would be nice to have it in the viewset I already have. Thanks. -
Django: 'created' cannot be specified for Order model form as it is a non-editable field
I've a model called Order, that stores information about the order placed by each user. This order has a field created that I want to display in the admin panel but I'm getting this error: FieldError at /admin/order/order/1/change/ 'created' cannot be specified for Order model form as it is a non-editable field. Check fields/fieldsets/exclude attributes of class OrderAdmin. models.py class Order(models.Model): token = models.CharField(max_length=100, blank=True, null=True) first_name = models.CharField(max_length=50, blank=True, null=True) last_name = models.CharField(max_length=50, blank=True, null=True) total = models.DecimalField(max_digits=10, decimal_places=2) email = models.EmailField(max_length=250, blank = True, verbose_name= 'Correo electrΓ³nico') last_four = models.CharField(max_length=100, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) shipping_address1 = models.CharField(max_length=100, blank=True, null=True) shipping_address2 = models.CharField(max_length=100, blank=True, null=True) shipping_department = models.CharField(max_length=100, blank=True, null=True) shipping_province = models.CharField(max_length=100, blank=True, null=True) shipping_district = models.CharField(max_length=100, blank=True, null=True) reason = models.CharField(max_length=400, blank=True, null=True, default='') class Meta: db_table = 'Order' ordering = ['-created'] def __str__(self): return str(self.id) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) product = models.CharField(max_length= 200) quantity = models.CharField(max_length= 200) size = models.CharField(max_length=200) price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name= 'PEN Price') image = models.ImageField(upload_to='images', blank=True, null=True) comment = models.CharField(max_length=200, blank=True, null=True, default='') uploaded_at = models.DateTimeField(auto_now_add=True) class Meta: db_table = "OrderItem" def sub_total(self): return self.quantity * self.price @property def image_filename(self): return self.image.url.split('/')[-1] def __str__(self): return self.product admin.py from β¦ -
Static django to link css file
I have an html file and a css file that run fine, but when I try to add the same html and css files to a django project and link them using static it no longer works. However, I don't think the issue is with the static link (css file is stored at app/core/css/core/index.css): {% load static %} <link rel="stylesheet" href="{% static 'core/css/index.css' %}"> Here is the entire html and css if the issue is not with the code above(the css is very long and I don't think the issue is within the css file, but you can see it working with no issue at https://jsfiddle.net/mfgqz0rj/): index.html, {% extends 'core/base.html' %} {% block head %} {% load static %} <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="author" content="colorlib.com"> <link href="https://fonts.googleapis.com/css?family=Poppins:400,800" rel="stylesheet" /> <link rel="stylesheet" href="{% static 'core/css/index.css' %}"> {% endblock %} {% block body %} <div class="s006"> <form> <fieldset> <legend>Search</legend> <div class="inner-form"> <div class="input-field"> <button class="btn-search" type="button"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"> <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 β¦ -
why the ajax like button is not working ?
I am trying to develop like button for post in homepage.Profile model is in one to one relationship with User model.The models are, class Profile(models.Model): Follwers=models.IntegerField(default='0') user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) bio=models.TextField(max_length=120,blank=True) location=models.CharField(max_length=30,blank=True) birth_date=models.DateField(null=True,blank=True) verified=models.BooleanField(default=False) ProfilePic=models.ImageField(upload_to='UserAvatar',blank=True,null=True,default='UserAvatar/ProfileFilled.svg') def __str__(self): return self.user.username @receiver(post_save,sender=User) def update_user_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() class post(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) Picture=models.ImageField(upload_to='PostMedia',blank=True,null=True) DatePosted=models.DateTimeField(default=timezone.now) Content=models.TextField(blank=True,null=True) def __str__(self): return self.Profile.user.username class Meta: ordering=['-DatePosted'] @property def like_count(self): return len(likes.objects.filter(post=self)) class likes(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) post=models.ForeignKey(post,on_delete=models.CASCADE) the url for ajax is urlpatterns=[ path('ajax/check_like',views.check_like,name='check_like'),] the corresponding view function is, def check_like(request): if request.user.is_authenticated: if request.method == 'POST': form = LikeForm(request.POST) if form.is_valid(): postid_id=request.POST['post'] checking=likes.objects.get(post__id=postid_id,Profile__user=request.user) if checking: checking.delete() U=1 return JsonResponse(U) else: create=likes.objects.create(post__id=postid_id,Profile__user=request.user) V=0 return JsonResponse(V) else: redirect('signup') while template is , {% if result %} <div class="infinite-container"> {% for p in result %} <div class="infinite-item"> <div class="PostHeader"> {% if p.Profile.ProfilePic %}<img src="{{ p.Profile.ProfilePic.url}}"/> {% else %}<img src="{%static "images/icons/ProfileFilled.svg" %}"/>{% endif%} <a href="/Profile/{{ p.Profile.user.username }}">{{ p.Profile.user.username }}</a> </div> {% if p.Picture %}<div class="ImageContainer"><img src="{{p.Picture.url}}"/></div>{% endif %} {% if p.Content %}<div class="Content"><p> {{ p.Content }}</p></div>{% endif %} <form id="like_form"> {% csrf_token %} <input type="hidden" name="post" id="post_id"value="{{ post.id }}"> <button id="likesubmit" type="submit"></button></form> <div class="SpriteContainer"> <label for="likesubmit"> {% if U %} <div class='Heart' style="color:#000000;">&#9825;</div><!-- &#9829 for filled heart &#9825 for empty heart--></div> {% endif %} {% β¦ -
Deploying Django application with SQL Database to Azure
I've built a simple Django application on my local Windows machine that connects to a SQL Server hosted on Azure by leveraging the Django-Pyodbc-Azure back end. I'm able to connect to the database fine on my local machine and my app runs without issue. However, I'm not in the process of deploying the application to Azure's app service and I'm running into problems. The deployment itself runs without issue, however the following error message shows up in my logs: Traceback (most recent call last): File "/home/site/wwwroot/antenv3.6/lib/python3.6/site-packages/sql_server/pyodbc/base.py", line 15, in <module> import pyodbc as Database ImportError: libodbc.so.2: cannot open shared object file: No such file or directory File "/home/site/wwwroot/antenv3.6/lib/python3.6/site-packages/sql_server/pyodbc/base.py", line 17, in <module> raise ImproperlyConfigured("Error loading pyodbc module: %s" % e) django.core.exceptions.ImproperlyConfigured: Error loading pyodbc module: libodbc.so.2: cannot open shared object file: No such file or directory My requirements.txt file looks as such: Django==2.1.4 django-pyodbc-azure==2.1.0.0 pyodbc==4.0.25 pytz==2018.7 And again... this runs fine locally on my Windows machine. But I get this error when I deploy to Azure. I suspect this has something to do with the Pyodbc backend not being installed correctly on Azure's LINUX based app service? Does anybody have experience resolving this? -
Passing Parameter for Queryset to Django Form
I am using a django (2.1) ModelMultipleChoice field for a form. I am trying to modify the queryset based on the slug in the URL. I am pretty certain I am missing something stupid. The Form: class SubdomainForm(forms.Form): # TODO Get the value slug from init slug = "camp" # Works well if value of slug set here. q = Feature2Subdomain.objects.all().select_related().filter(subdomain__slug=slug) choices = forms.ModelMultipleChoiceField( queryset = q, widget = forms.CheckboxSelectMultiple, ) def __init__(self, *args, **kwargs): slug = kwargs.pop('slug', None) # Correctly obtains slug from url super(SubdomainForm, self).__init__(*args, **kwargs) The View: class SubdomainDetailView(FormView): template_name = "guide/subdomain-detail.html" form_class = SubdomainForm def get_form_kwargs(self, form_class=SubdomainForm): s = dict(slug = self.kwargs['slug']) return s URLS.py urlpatterns = [ path('subdomain/<slug:slug>/', SubdomainDetailView.as_view(), name="subdomain-detail" ), ..... Obviously, the idea is that the slug from the URL is used to modify the queryset. (in the example the value of the slug is "camp" I can obtain the value of the slug in the init method for the form, and can call super() to instantiate the form. However, I can't figure out how to access the value in the "choices" line of the form. If I hard code the value of slug="camp" I can get the whole thing to work properly. β¦ -
Django dropdown dependencies on admin
I started with django for a short time, and I am trying to create an application where only the admin interface will be used. I have a situation where the user after selecting the 'freguesia' will show the 'rua' that belongs to this 'freguesia'. I found some forums explaining how to do in frontoffice, but nothing relative in the admin interface. My models: class freguesia(models.Model): freguesia_nome = models.CharField("Freguesia",max_length=200) class rua(models.Model): rua_id_freg = models.ForeignKey(freguesia, on_delete=models.CASCADE) rua_nome = models.CharField("Rua",max_length=200) //ANOTHER APP class avaria(models.Model): avaria_freguesia = models.ForeignKey(freguesia, on_delete=models.CASCADE,verbose_name="Freguesia") avaria_rua = models.ForeignKey(rua, on_delete=models.CASCADE,verbose_name="Rua") https://i.stack.imgur.com/R77mi.png https://i.stack.imgur.com/H7juQ.png https://i.stack.imgur.com/Bc1Zq.png