Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
expected token ':', got '}' in Django
I am receiving the error message mentioned in the subject of this post when trying to acccess on of my views in Django. I've tried to look at other similar questions but they seemingly frequently have to do with a .html template. In my case, this view is rendering a .docx file. Full Traceback Request Method: POST Request URL: http://127.0.0.1:8000/AESCreate Django Version: 1.11 Python Version: 2.7.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'bootstrap_modal_forms', 'smart_selects', 'unit'] 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 "/Library/Python/2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/Library/Python/2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/andrews/Desktop/WBU/web_unit/unit/views.py" in AESCreate 867. doc.render(context) File "/Library/Python/2.7/site-packages/docxtpl/__init__.py" in render 266. xml_src = self.build_xml(context, jinja_env) File "/Library/Python/2.7/site-packages/docxtpl/__init__.py" in build_xml 229. xml = self.render_xml(xml, context, jinja_env) File "/Library/Python/2.7/site-packages/docxtpl/__init__.py" in render_xml 217. raise exc Exception Type: TemplateSyntaxError at /AESCreate Exception Value: expected token ':', got '}' views.py def AESCreate(request): reference = request.POST.get('AES_Refs') manifest = Manifests.objects.all().filter(reference__reference=reference) order = Orders.objects.get(reference=reference) today = date.today() sum = Products.objects.filter( Q(manifests__reference__reference=reference)).annotate( total_quantity=Sum('manifests__cases') ) doc = DocxTemplate("AEStemplate.docx") totalFOB = 0 totalCases = 0 for item in manifest: totalFOB += item.cases * item.FOB totalCases += … -
Perform translation (internationalization) using ugettext_lazy in models.py for a dynamic variable
I have a django project where there are multiple models defined and each model have some set of fields with choice fields. These values are being displayed on template using a loop. I have multiple languages defined and using ugettext_lazy, I am able to show the translated value as per the language selected by user. Now I am trying to move these values into database, fetch them and use it in ugettext_lazy for translation. e.g. _(value_from_db) Problem is when using from database, the value doesn't translate whereas when using it as hardcoded e.g. _("translated_val") models.py from django.utils.translation import ugettext_lazy as _ from translated_fields import TranslatedField class ModelClass(models.Model): choices_values = ( (dataframe[(dataframe['name'] == 'State1')]['code'].item(), _("State1")), (dataframe[dataframe['name'] == 'State2']['code'].item(), _(dataframe[dataframe['name'] == 'State2']['value'].item())), (State3, _("State3")) ) In the above example, the translation works properly for State1, State3 but not for State2. I expect State2 to be translated on my template. P.S. All the translation activities have been done properly and are working (if I replace the dataframe fetch for state2 with hardcoded value, it gives the proper tranlation and also the dataframe fetches the same value as the one I had hardcoded) Thanks for the help. -
Weasyprint not rendering images in production
I have a django app running in a nginx server, every static file is laoded correctly, but, but when i'm using weaseyprint to create a pdf, the images are not showing. Using runserver in localhost, the images are shown. Nginx Cinfiguration: location /static/ { autoindex on; alias /var/www/app.com/static; } App settings: STATIC_URL = '/static/' STATIC_ROOT = "/var/www/ciber-seguro.com/static/" File creation: html_string = render_to_string('budget/contract.html', context) html = HTML(string=html_string, base_url=request.build_absolute_uri('/')) pdf = html.write_pdf(stylesheets=[CSS('web/static/css/contract.css')]) dirname = "./files/budgets" filename='budget_'+str(contract.id)+".pdf" response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="'+filename+'"' It's my first time with nginx and django, so its problably a simple problem, but i'm not able to find it. I have the felling it has to do with nginx, but i don't really have a clue. -
Is there a way to execute html inside of a template variable that is a table?
I am creating a website using Django and I have taken a pandas dataframe and stored it as a template variable and passed it to the render request. I would like to make some columns form elements but have been unsuccessful into how to do that. I have already tried applying the function to the pandas dataframe in order to add the proper HTML to each element in the column. However, the HTML itself shows up on the actual site. Here is my python code: def optimizer(request): df = Optimizer.get_daily_roster('E:\website\optimizer\Predictions.csv') df = df.drop(columns=['Name + ID', 'Game Info', 'Unnamed: 0', 'Unnamed: 0.1', 'name']) df = df.rename(columns={'TeamAbbrev': 'Team', 'AvgPointsPerGame': 'Predicted FP'}) df['Predicted FP'] = df['Predicted FP'].apply(lambda x: round(float(x), 2)) df['Predicted FP'] = df['Predicted FP'].apply(lambda x: "<input type='text' value=" + str(x) + ">") df['Min Exposure'] = 0 df['Max Exposure'] = 1 # cols_to_values = df.to_dict(orient='list') # cols_to_values = {x.translate({32: None}): y # for x, y in cols_to_values.items()} html_table = df.to_html(index=False, justify='left', classes=[ 'table table-bordered table-striped table-hover table-responsive table-sm, container-fluid']) return render(request, 'optimizer/optimizer.html', {'player_table': html_table}) And here is my HTML: {% extends "optimizer/base.html" %} {% block content %} <h1>Optimizer</h1> <form method="post"> <input type="submit" value="Generate Lineups"> <div class="table-responsive"> {{ player_table |safe }} </div> </form> {% … -
Getting total debt and remaining debt list with Django
I am working with django-rest-api-framework. I want to list the customers' debts and show the remaining amount. Customer A has four debt records. A customer has "totalDebt" and "totalReceived" fields. I want to calculate the total remaining debt record of each customer. But I want him to calculate on one line. And I want to print it out as json {'customer__customerKey': UUID('f76d64f9-d181-45b7-b8da-af7fb5238cfa'), 'totalDebt__sum': Decimal('50.00'), 'receivedAmount__sum': Decimal('15.00')}, {'customer__customerKey': UUID('f76d64f9-d181-45b7-b8da-af7fb5238cfa'), 'totalDebt__sum': Decimal('100.00'), 'receivedAmount__sum': Decimal('15.00')}] {'customer__customerKey': UUID('f76d64f9-d181-45b7-b8da-af7fb5238cfa'), 'totalDebt__sum': Decimal('50.00'), 'receivedAmount__sum': Decimal('9.00')}, {'customer__customerKey': UUID('f76d64f9-d181-45b7-b8da-af7fb5238cfa'), 'totalDebt__sum': Decimal('100.00'), 'receivedAmount__sum': Decimal('30.00')}] {'customer__customerKey': UUID('1db32404-272c-47da-801b-965151627afc'), 'totalDebt__sum': Decimal('250.00'), 'receivedAmount__sum': Decimal('80.00')}, {'customer__customerKey': UUID('1db32404-272c-47da-801b-965151627afc'), 'totalDebt__sum': Decimal('250.00'), 'receivedAmount__sum': Decimal('95.00')}, -
How to add different models to only one model in django?
I have some models that are used to make one order per dining table. My goal is to have different dining tables, these always have a total order and the total order has individual orders. I have difficulties when i create a second dining table, with a second total order, to avoid taking orders (relationship) from the first table. How can i make a total order that has his own orders, without any relationships from other orders? Here my models: class Order(models.Model): Beer = models.ForeignKey(Beer, on_delete=models.SET_NULL, blank=True, null=True, related_name='beer') SoftDrink = models.ForeignKey(SoftDrink, on_delete=models.SET_NULL, blank=True, null=True, related_name='soft_drink') ForeignBeer = models.ForeignKey(ForeignBeer, on_delete=models.SET_NULL, blank=True, null=True, related_name='foreign_beer') Liquor = models.ForeignKey(Liquor, on_delete=models.SET_NULL, blank=True, null=True, related_name='liquor') Wine = models.ForeignKey(Wine, on_delete=models.SET_NULL, blank=True, null=True, related_name='wine') BarDrink = models.ForeignKey(BarDrink, on_delete=models.SET_NULL, blank=True, null=True, related_name='bar_drink') Meal = models.ForeignKey(Meal, on_delete=models.SET_NULL, blank=True, null=True, related_name='meal') class TotalOrder(models.Model): Order = models.ManyToManyField(Order, related_name='order') Total_Price = models.DecimalField(default=0, max_digits=6, decimal_places=2) class Table(models.Model): Number = models.IntegerField(unique=True) Total_Order = models.ForeignKey(TotalOrder, on_delete=models.SET_NULL, related_name='total_order', blank=True, null=True) Thanks in advance :D -
Connect MariaDB Column Store to Django
I'm trying to build a dockerized app with django, mariadb for analytical purposes. Unfortunately getting the following error, which i cant connect to columnstore mariadb database from django. dmd_web | Traceback (most recent call last): dmd_web | File "/usr/local/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection dmd_web | self.connect() dmd_web | File "/usr/local/lib/python3.6/site packages/django/db/backends/base/base.py", line 194, in connect dmd_web | self.connection = self.get_new_connection(conn_params) dmd_web | File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 236, in get_new_connection dmd_web | return Database.connect(**conn_params) dmd_web | File "/usr/local/lib/python3.6/site-packages/MySQLdb/__init__.py", line 84, in Connect dmd_web | return Connection(*args, **kwargs) dmd_web | File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 166, in __init__ dmd_web | super(Connection, self).__init__(*args, **kwargs2) dmd_web | MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") dmd_web | dmd_web | The above exception was the direct cause of the following exception: dmd_web | dmd_web | Traceback (most recent call last): dmd_web | File "manage.py", line 15, in <module> dmd_web | execute_from_command_line(sys.argv) dmd_web | File "/usr/local/lib/python3.6/site- packages/django/core/management/__init__.py", line 371, in execute_from_command_line dmd_web | utility.execute() dmd_web | File "/usr/local/lib/python3.6/site- packages/django/core/management/__init__.py", line 365, in execute dmd_web | self.fetch_command(subcommand).run_from_argv(self.argv) dmd_web | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv dmd_web | self.execute(*args, **cmd_options) dmd_web | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute dmd_web | self.check() dmd_web | File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check … -
Get users who belongs to groups
I´m trying to get queryset of users who are in group Creator and in a group Teacher, at the same time. test.py where i send array of groups i want to filter: def test_admin_create_authenticated(self): data = {"data": {"alert_type":"system", "text": "UnitTest"}, "filters":{"groups":['Teacher', 'Creator'], "together": True}} url = reverse('admin_alerts-list') response = self.client.post(url, json.dumps(data), content_type="application/json") self.assertEqual(response.status_code, status.HTTP_200_OK) views.py: Here i would like to make a q_objects which will filter groups by name: if 'groups' in filters: print(filters['groups']) try: for group in filters['groups']: q_objects.add(Q(groups__name=group), variable) except: q_objects.add(Q(groups=filters['groups']), variable) And then find all users who are in those groups: print(q_objects) users = User.objects.filter(q_objects) print(users.query) print(users) Terminal: ['Teacher', 'Creator'] (AND: ('groups__name', 'Teacher'), ('groups__name', 'Creator')) SELECT "auth_user"."id", "auth_user"."password", "auth_user"."last_login", "auth_user"."is_superuser", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."date_joined" FROM "auth_user" INNER JOIN "auth_user_groups" ON ("auth_user"."id" = "auth_user_groups"."user_id") INNER JOIN "auth_group" ON ("auth_user_groups"."group_id" = "auth_group"."id") WHERE ("auth_group"."name" = Teacher AND "auth_group"."name" = Creator) <QuerySet []> Why my q_objects doesn´t work? I have one user who is in those 2 groups. -
Set GOOGLE_APPLICATION_CREDENTIALS environment variable in VSCode debugger
I'm testing Google Cloud Pub/Sub on my Django project using VSCode on my Mac, and I'm having some problems setting GCP environment variables during debugging tests, specifically the GOOGLE_APPLICATION_CREDENTIALS environment variable. I am able to set the GOOGLE_APPLICATION_CREDENTIALS for running server and/or tests locally with export GOOGLE_APPLICATION_CREDENTIALS="path/to/json_credential_file.json" in a shell, but as the VSCode debugger runs in a separate shell the env variable is not set when debugging tests. I tried adding the same value to the env key in launch.json: "env": { "GOOGLE_APPLICATION_CREDENTIALS": "path/to/json_credential_file.json" } But it still complains about GOOGLE_APPLICATION_CREDENTIALS not being set: oauth2client.client.ApplicationDefaultCredentialsError: The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information. Any ideas? -
Django multiple ModelForms from one Model
I need to implement a transaction with a step by step process wherein the user can input the details in step 1 and then process the inputted data which will do some calculations. The user can then proceed to step 2 which displays the initial result and he/she can input additional parameters to manipulate the results. I need to store all user inputs in one model so that if the user cancels the process, all data that was initially stored will be deleted. I am a newbie in django and python so if anyone know how to solve this problem I would really appreciate it. This is what I've tried so far: In my models.py I have: class Calculate(models.Model): date_created = models.DateField(auto_now_add=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) csv = models.FileField(upload_to='files/') param1 = models.CharField() param2 = models.CharField() param3 = models.CharField() In my forms.py I have: class DetailsInputForm(forms.ModelForm): class Meta: model = Analysis fields = ('date_created', 'csv',) class ParamInputForm(forms.ModelForm): class Meta: model = Analysis fields = ('param1', 'param2', 'param3',) In my views.py I have: class DetailsInputView(LoginRequiredMixin, CreateView): model = Calculate form_class = DetailsInputForm template_name = 'step1.html' login_url = 'login' success_url = reverse_lazy('step2') class ParamInputView(LoginRequiredMixin, CreateView): model = Calculate form_class = ParamsInputForm template_name = … -
File "/Users/susanalokozay/FinalProject/lib/python3.7/site-packages/django/urls/conf.py", line 39, in include
File "/Users/susanalokozay/FinalProject/lib/python3.7/site-packages/django/urls/conf.py", line 39, in include 'Specifying a namespace in include() without providing an app_name ' django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. -
How to setup a Django-site where users have different permissions for different projects
Kind stacky! Hopefully you can help me out. I'm trying to workout a framework on which I can relatively easily develop django-apps and distribute them to the users. Users can use these apps within a 'project' environment, so the data they see in that app is only related to the project they are currently looking at. I'm not referring to Django-projects here, but projects as in a task on which multiple people are working together. :) Users should be able to create a project and invite other users. If a user has no permission for a certain project he cannot access the project. Questions that are spooking through my head are: How do I need to setup my model? How do I go about setting up permissions? How do I make sure they can not access project data to which they don't have permissions. I understand there is not one true solution, but I am looking for recommendations on best practices or working examples. I just don't know how to start. I already searched the internet extensively but I can't find anything that resembles what I want to do. My line of thought currently is to create a project class … -
IntegrityError at /registerdoctor.html NOT NULL constraint failed: auth_user.first_name
I created a Doctor model having a OneToOneField with the Django User model. When I hit the 'Sign Up' button I get an Integrity Error : "IntegrityError at /registerdoctor.html NOT NULL constraint failed: auth_user.first_name" Can someone tell me how do I can fix the error i.e. what changes I should make and where? models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Doctor(models.Model): doctor = models.OneToOneField(User,on_delete=models.CASCADE) #additional exp = models.PositiveIntegerField() phone_no = models.IntegerField() def __str__(self): return self.doctor.username views.py from django.shortcuts import render,redirect from django.contrib.auth.models import User,auth from django.contrib import messages from app1.models import Doctor def HomePage(request): return render(request,'homepage.html') def RegisterUser(request): if request.method =="POST": first_name = request.POST["fname"] last_name = request.POST["lname"] email_id = request.POST["mail"] password1 = request.POST["pass1"] password2 = request.POST["pass2"] username = request.POST["username"] if password1==password2: if User.objects.filter(email=email_id).exists(): messages.info(request,"This Email ID is already Registered!") return redirect("registeruser.html") else: if User.objects.filter(username=username).exists(): messages.info(request,"Username taken!") return redirect("registeruser.html") else: user = User.objects.create_user(first_name=first_name,last_name=last_name, email=email_id,password=password1,username=username) user.save() return redirect("/") else: messages.info(request,"Passwords Not Matching!") return redirect("registeruser.html") return redirect("/") else: return render(request,'registeruser.html') def RegisterDoctor(request): if request.method == "POST": first_name = request.POST.get("finame") last_name = request.POST.get("laname") email_id = request.POST.get("emailid") username = request.POST.get('username') phone = request.POST.get("phno") exp = request.POST.get("doc_exp") password1 = request.POST.get("userpassword") password2 = request.POST.get("conpassword") if password1==password2: if User.objects.filter(email=email_id).exists(): messages.info(request,"This … -
How to upload a file outside the admin in wagtail
I want to set up a form that allows users to upload files (pdf, jpeg, docx, etc) from outside the Wagtail admin panel. But the form leaves the filefield out on my html page. Any advice would be great thanks! models.py class FormField(AbstractFormField): page = ParentalKey('FormPage', related_name='form_fields') class FormPage(AbstractEmailForm): template = "formsubmission.html" file = models.FileField(upload_to='uploads/', blank=True, null=True) submit_success = models.CharField(max_length=100, blank=False, null=True) submit_error = models.CharField(max_length=100, blank=False, null=True) content_panels = AbstractEmailForm.content_panels + [ FieldPanel('submit_success'), FieldPanel('submit_error'), InlinePanel('form_fields', label='Form Fields'), FieldPanel('file') ] htmlpage.html {% extends 'base.html' %} {% load wagtailcore_tags %} {% load static %} {% block content %} <h1>page.title</h1> <div class="container"> <form action="{% pageurl page %}" method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit"> </form> {% endblock %} -
How to do Filtering in Djnago?
I have a page where all transaction records are displayed. I want to narrow down the search for key points that are visible in the screenshot. How to implement a search? I tried through a filter(), but I notice that it is somehow inconvenient. Saw that can filter through Q... if request.method == 'POST': search_form = SearchForm(request.POST) if search_form.is_valid(): date1 = date(2000, 5, 2) date2 = date.today() contractor = None if search_form.cleaned_data['date1st']: date1 = search_form.cleaned_data['date1st'] if search_form.cleaned_data['date2st']: date2 = search_form.cleaned_data['date2st'] if search_form.cleaned_data['contractorName']: contractor = search_form.cleaned_data['contractorName'] print(date1) print(date2) paymentsss = Transaction.objects.select_related('currency', 'payment_source__payment_type', 'deal__service', 'deal__service__contractor').filter( payment_date__range=[date1, date2], deal__service__contractor__name=contractor).order_by('-id')[:2700] search_form = SearchForm() paginator = Paginator(paymentsss, 25) page = request.GET.get('page') try: payments = paginator.get_page(page) except(EmptyPage, InvalidPage, PageNotAnInteger): payments = paginator.page(1) data = {'payments': payments, 'form': search_form} return render(request, "payments.html", data) -
In django which is better io.StringIO or ContentFile
What is the difference between io.StringIO() and ContentFile? Which one is better performance-wise? -
Deploy Problems with Ubuntu + Django + Apache2
I'm a beginner to Django and apache2. Here's my server environment: ubuntu 18.04 + Apache/2.4.29 (Ubuntu) + Python 3.6.8 + Django 2.2.6 + MySQL 5.7 I follow the Django document: https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/modwsgi/ and also some solution from InterNet. Here's my /etc/apache2/sites-available/gostar.conf now: <VirtualHost *:80> LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so AddHandler wsgi-script.py DocumentRoot /var/www/html/kyle/GoStar4F1/src/GoStar # Alias /media/ /media/ # Alias /static/ /static/ LoadModule wsgi_module modules/mod_wsgi.so # <Directory /media> # Require all granted # </Directory> # <Directory /static> # Require all granted # </Directory> WSGIDaemonProcess GoStar python-path=/var/www/html/kyle/GoStar4F1/src/GoStar \ python-home=/home/kyle/testDjango WSGIProcessGroup GoStar WSGIScriptAlias / /var/www/html/kyle/GoStar4F1/src/GoStar/GoStar/wsgi.py \ process-group=GoStar application-group=%{GLOBAL} <Directory /var/www/html/kyle/GoStar4F1/src/GoStar/GoStar> <Files wsgi.py> #Require all granted Order deny,allow Allow from all </Files> </Directory> And I did the following command: $ sudo a2ensite gostar.conf $ sudo systemctl reload apache2 #response: Job for apache2.service failed because the control process exited with error code. See "systemctl status apache2.service" and "journalctl -xe" for details. so I $ systemctl status apache2.service #response: ● apache2.service - The Apache HTTP Server Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: active (running) (Result: exit-code) since Tue 2019-10-29 13:56:38 CST; 27min ago Process: 28191 ExecStop=/usr/sbin/apachectl stop (code=exited, status=1/FAILURE) Process: 29149 ExecReload=/usr/sbin/apachectl graceful (code=exited, status=1/FAILURE) Process: 28364 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS) Main PID: 28375 … -
Django application server requirement with ubuntu + apache + mod_wsgi
I need your guidence on setting up my production server for django application. Below are the details of my application . Its a simple website which connects 3 database/applications that is already available in 3 separate VM's. The 3 applications are: 1) MSSQL database(which will provide details of a parent table(model) and 15 or 20 child tables(model). when each record from the parent model is opened it fetches the details of other child tables and display them in the page) 2) Document management system to stream the files(average of 10 files with each documents with 150-200 kb size of each document) related to the records that are fetched with the previous step. 3) Mysql database (which will give few more details related to the parent model from the parent model) Now my new VM which we are going to setup should have a simple RDBMS created with postgreg to hold the basic details of django and the website users along with python and django. The current user base is 5-6 users at a time and may grow to 10 -12. Can some one recommend a capacity planning for the above requirement for DJANGO+ UBUNTU + APACHE + MOD_WSGI( please suggest … -
How to fix the html code in django template
The template has an issue. That is tag in my base.html shows that there is no closing tag and in list.html file the warnings are about {% already exists(expected endif instead of endfor) Python 3.8.0rc1,pip 19.3.1,and the django version is 2.2.6 list.html <ul> <li {% if not category %}class="selected"{% endif %}> <a href="{% url "shop:product_list"%}">All</a> </li> {% for c in categories %} <li {% if category.slug == c.slug %}class="selected"{% endif %}> <a href="{{ c.get_absolute_url }}">{{ c.name }}</a> </li> {% endfor %} </ul> base.html <head> <meta charset="utf-8" /> <title>{% block title %}My shop{% endblock %}</title> <link href="{% static" css/base.css" %}" rel="stylesheet"> </head> The attribute name is missing(points at c.slug). I'm an amateur,I've just started working with django,please do help,Thanks in adavance. -
Django urls.py: best way to not have a page number in the first page of a list view?
Right now I have a list view that displays 10 posts per page: The urls would be something like this: www.example.com/posts/1 (First page with 10 results) www.example.com/posts/2 (Next page with 10 results) and my urls.py looks something like this: path('posts/<int:page>', PostList.as_view(), name='post-list'), I want to be able to have the first page of posts also visible when there is no number, for example: www.example.com/posts (First page with 10 results) The only way that I have been able to solve this is by adding another line in the urls.py that points to the same view and that has the same name. path('posts', PostList.as_view(), name='post-list'), path('posts/<int:page>', PostList.as_view(), name='post-list'), Is this the appropriate way of doing this or is there a better way? Many thanks! -
Docker run application in a volume
In my django docker app i would to use a volume for manage my application file here is my Dockerfile: FROM python:3.6-alpine EXPOSE 8000 RUN apk update RUN apk add --no-cache make linux-headers libffi-dev jpeg-dev zlib-dev RUN apk add postgresql-dev gcc python3-dev musl-dev VOLUME /var/lib/cathstudio/data WORKDIR /var/lib/cathstudio/data COPY ./requirements.txt . RUN pip install --upgrade pip RUN pip install -t /var/lib/cathstudio/data -r requirements.txt ENV PYTHONUNBUFFERED 1 ENV PYTHONPATH /var/lib/cathstudio/data COPY . /var/lib/cathstudio/data ENTRYPOINT python /var/lib/cathstudio/data/manage.py runserver 0.0.0.0:8000 but when i run my app: docker run -d -it --rm --link postgres:postgres --name=cathstudio myrepo/app_studio:latest i get python: can't open file '/var/lib/cathstudio/data/manage.py': [Errno 2] No such file or directory the same also if i in my Dockerfile write just ENTRYPOINT python manage.py runserver 0.0.0.0:8000 where is my file wrong? how can i run my app using a volume for storing app files? So many thanks in advance -
Django AJAX working but test case failing in POST request
So I have this unit test: def test_delete_product(self): self.api_client.login(username=self.username, password=self.password) path = self.get_url_for_test_against_endpoint('/product/delete/') data = {'id': self.product.id} response = self.api_client.post(path=path, data=json.dumps(data), content_type='application/json') self.assertEqual(response.status_code, 302) self.assertFalse(Product.objects.filter(id=self.product.id).exists()) and this view def post(self, request): pid = request.POST.get('id') get_object_or_404(Product, id=pid).delete() return redirect('product:products') My entry in urls.py is path('product/delete/', product_delete_view, name='product_delete') The AJAX I am using to call this view is: <script> const url = "{% url 'product:product_delete' %}" var id = "{{ product.id }}" var intId = parseInt(id) const data = { id: intId, csrfmiddlewaretoken: '{{ csrf_token }}' , contentType:'application/json'} $('#{{ product.id }}').click(function () { $.post(url, data, function (data, status) { console.log(`${data} and status is ${status}`) location.reload(true) }) }) </script> What works: When I call this view through ajax, everything works fine and the product is deleted. What does NOT work When I run the test, it fails because response.status_code returns 404. While trying to find out what the problem is, I used pdb.set_trace() in view and I found that request.POST.get('id') returns None. If I hard code pid to 1 test case passes which means in the view, it is unable to get id from the request which is weird because it is able to do that same through ajax call. If I do … -
Apache24 Django Don't download files. Not found. The requested resource was not found on this server
I am setting django project to Apache24 for windows. Everything works except download file from client. Upload also works. I have Hierarhical directory by attachments//. If I set BEDUG=TRUE then downloads working. Help me, please, where i wrong? below httpd.conf LoadFile "c:/<>/python/python36/python36.dll" LoadModule wsgi_module "c:/envs/myproject/lib/site-packages/mod_wsgi/server/mod_wsgi.cp36-win_amd64.pyd" WSGIScriptAlias / "c:/<myproject>/wsgi.py" WSGIPythonHome "c:/envs/myproject" WSGIPythonPath "c:/<myproject>" Alias /static/ "c:/<myproject>/static/" <Directory "c:/<myproject>/static"> Require all granted </Directory> <Directory c:/<myproject>> <Files wsgi.py> Require all granted </Files> </Directory> # Другие полномочия, если потребуются <Directory c:/<myproject>/attachments> Require all granted </Directory> -
How to access my domain on digital ocean droplet?
I amt trying to deploy a django website on digitalocean server.I am new to digital ocean.i added my domain on my droplet.when i access my domain it shows site can't be reached message.How can i activate my domain.Any help is appreciated. -
Django NoReverseMatch when trying to logout
I have a django view function signout that I want to call form a form/template. When i click logout, it calls the function but the redirect after doesnt work. I get the message Reverse for '<WSGIRequest: POST '/account/signout'>' not found. '<WSGIRequest: POST '/account/signout'>' is not a valid view function or pattern name. Urls.py urlpatterns = [ path('register', views.register, name='register'), path('login', views.login, name='login'), path('signout', views.signout, name='signout'), path('dashboard', views.dashboard, name='dashboard'), ] Views.py def signout(request): if(request.method == 'POST'): auth.logout(request) messages.success(request, 'You are logged out!') return redirect(request, 'index') Template form <form action="{% url 'signout'%}" id="logout" method="POST"> {% csrf_token %} <input type="hidden"> <button type="submit" class="btn btn-primary btn-sm"><i class="fas fa-sign-out-alt"></i> Log Out</button> </form> What is going wrong?? The rest of routes work just fine and they are declared the same as signout.