Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
redirect in django does work in POST method
i have views in django that is called by $.post() method of jquery that is working fine. But when i redirect inside that post it's not redirecting me but outside its redirecting me. here is view called by jquery $.post() @csrf_exempt def order_detail(request): category_name = request.session.get('category_name') category = Category.objects.get(name=category_name) price = Price.objects.get(category=category) if request.session['industry_name']: industry_name = request.session.get('industry_name') industry = Industry.objects.get(name=industry_name) images = SampleImages.objects.filter(category=category, industry=industry) colors = SampleColor.objects.all() else: images = SampleImages.objects.filter(category=category) colors = SampleColor.objects.all() if request.method == 'POST': image_list = request.POST.getlist('idSelectedImages[]') color_list = request.POST.getlist('idSelectedColors[]') package_price = request.POST.get('packagePrice') package_name = request.POST.get('packageName') if image_list: for image_id in image_list: request.session['image_list']['{}'.format(image_id)] = image_id request.session.modified = True if color_list: for color_id in color_list: request.session['color_list']['{}'.format(color_id)] = color_id request.session.modified = True return redirect('order:order_brief') else: request.session['image_list'] = {} request.session.modified = True request.session['color_list'] = {} request.session.modified = True return render(request, 'order/order_detail.html', {'images': images, 'colors': colors, 'price': price}) and urls.py app_name = 'order' urlpatterns = [ path('', views.index, name='index'), path('order/detail/', views.order_detail, name='order_detail'), path('order/brief/', views.order_brief, name='order_brief'), ] -
printing db values to html django
can anyone help? I want to print some counts from the DB (total records where the complete field = true and another when it equals false. What have I done wrong in the below? Thanks VIEWS def task_count(request): completetasks = Todo.objects.filter(complete=True).count() incompletetasks = Todo.objects.filter(complete=False).count() return render(request, 'counts.html') URLS urlpatterns = [ url(r'^$', views.todo, name='index'), url(r'^create/$', views.create_task, name='create'), url(r'^counts/$', views.task_count, name='counts'), COUNTS.HTML {% extends 'base.html' %} {% block content %} <br><br><br> {% if user.is_authenticated %} <div class="container"> {% filter upper %} <h3>Notes for task</h3> {% endfilter %} </div> {{ completetasks }} {% else %} <h2><a href="/login">Login</a></h2> {% endif %} {% endblock %} -
Django-Tables2 LinkColumn link goes to wrong item
I have a Django project and I am having issues with the hyperlink (LinkColumn from Django-tables2) going to the incorrect entry and I cannot figure out why it is occurring or how to fix it. Very specifically, I can go to the admin view and create a publication. When it comes to setting the author (a.k.a. pi) or sample, there is a drop down menu for foreign key fields (sample/pi) that shows all existing entries from which I can choose one. When I choose a sample and pi then look at the table rendering, the hyperlink is there for the sample, pi, and the publication title. The publication title correctly takes me to the publication_detail page but the hyperlink for the sample will take me to a sample detail page, but it is not the same sample I selected. I have the same issue for the author; it takes me to the detail view page of AN author, just not the one I selected for the admin page. I use django-tables2 several times throughout the project and like how the tables are rendered, but cannot figure out how to address this problem. I have included some of my code (please … -
Multiple object-create with form and validation
I try to make multiple objects with one form. Without validation - all works perfectly. When I try to validate - I can't get Tram object. Model Gate has ForeignKey Tram. During creating object, user is allowed to create the same Gate for multiple Tram's. Unfortunatelly, Gate can be various type of object, and for each type of Gate, validation unique_together is various. I overwrited validate_unique in models.py. models.py class Gate(models.Model): GATE_TYPE = ( ('BJC', u'Bramka jakościowa - człon'), ('BJW', u'Bramka jakościowa - wózek'), ('IKS', u'Inspekcja końcowa - Solaris'), ('IKK', u'Inspekcja końcowa - klient') ) CAR_SYMBOLS = ( ('C1', u'C1'), ('C2', u'C2'), ('C3', u'C3'), ('C4', u'C4') ) BOGIE_TYPES = ( ('WN1', u'Wózek napędowy 1'), ('WN2', u'Wózek napędowy 2'), ('WT', u'Wózek toczny'), ('WN3', u'Wózek napędowy 3'), ('WN4', u'Wózek napędowy 4'), ) GATE_STATUSES = ( ('R', u'Realizacja'), ('O', u'Ocena DZJ'), ('P', u'Ponowna realizacja'), ('A', u'Archiwum') ) GATE_GRADES = ( ('OK', u'Zaakceptowany'), ('NOK', u'Odrzucony') ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) type = models.CharField(choices=GATE_TYPE, default='BJC', max_length=3) tram = models.ForeignKey(Tram, null=True, on_delete=models.CASCADE) bogie = models.ForeignKey(Bogie, null=True, on_delete=models.CASCADE) bogie_type = models.CharField(choices=BOGIE_TYPES, null=True, max_length=3) car = models.CharField(choices=CAR_SYMBOLS, max_length=2, null=True) area = models.ForeignKey(OperationArea, null=True, on_delete=models.CASCADE) operation_no = models.CharField(max_length=6) name = models.CharField(max_length=200) content = models.TextField() gate_status = models.CharField(choices=GATE_STATUSES, default='R', … -
Django - limit key size on unique_together columns
Using MySQL, I am trying to have a table with a composite key of multiple fields. The issue is that some of the fields are large (255 - 1024 length), if I try to run the migration, I will get: django.db.utils.OperationalError: (1071, 'Specified key was too long; max key length is 767 bytes') Instead of increasing the DB's key length (or changing some other DB / table settings), I found out that I can just limit the value of the field used as a key in the migration file so that it remains within the max key length, like this: ALTER TABLE <table> ADD UNIQUE KEY `<table>_composite_key` (`col1`, `col2`(75), `col3`, `col4`, `col5`(150)); However, this is an issue if I were to change the db engine, as that syntax might not be compatible with other. So I'm wondering is there a way to impose limit for each field in unique_together? Thanks in advance! -
IntegrityError in TestCase runs after updating to Django 2.0
I upgraded from Django 1.11 to Django 2.0 and my tests started failing. I have 7 TestCase classes and all use the setUpTestData provided by Django. When I run them all together one of them fails to set up because of an psycopg2.IntegrityError: duplicate key value violates unique constraint "doctors_doctor_pkey". When I run one of those TestCase classes alone it works fine. It seems like they're influencing each other in some way, but it's strange that it would fail after upgrading to Django 2.0. I've also noticed it's not at the create() it's at the save(). In the setup for the dashboards app I have some creation data: cls.d1 = doctor_models.Doctor.objects.create(email="johndoe@example.com", name="John Doe", specialization=cls.s1, premium=True, premium_price=4310, consultation_price=341) ... cls.b1 = doctor_models.DoctorBooking.objects.create(clinic=cls.c1, doctor=cls.d1, status=2, premium_booking=True, patient_name="example", patient_phone_number="+9747721234", confirmed_date=datetime.strptime( "16 Jun 2017 14:22:26:000 +0300", receive_format), handled_on=datetime.strptime( "17 Jun 2017 14:22:26:000 +0300", receive_format)) The second line from above would call it's save() function that would call save() on cls.d1 def save(self, *args, **kwargs): if self.doctor.premium: self.premium_booking = True else: self.premium_booking = False super(DoctorBooking, self).save(*args, **kwargs) self.doctor.save() # <- here it raises an IntegrityError This is the simplest code I could extract, but this happens all over for different classes. To reiterate this gives … -
dj-stripe webhook product not created
I'm trying to set up dj-stripe webhooks on my development server. I'm using ngrok.io and the webhooks are coming through ok but when I create a new product or plan in the Stripe dashboard, I initially get a http 500 error aka "POST /stripe/webhook/ HTTP/1.1" 500 0 and on the first retry it goes through but the product isn't created. The traceback for the 500 error is below: Traceback (most recent call last): File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/models.py", line 3389, in from_request obj.process(save=False) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/models.py", line 3448, in process self.event = Event.process(self.json_body) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/models.py", line 1486, in process ret.invoke_webhook_handlers() File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/models.py", line 1498, in invoke_webhook_handlers webhooks.call_handlers(event=self) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/webhooks.py", line 104, in call_handlers handler_func(event=event) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/event_handlers.py", line 146, in other_object_webhook_handler _handle_crud_like_event(target_cls=target_cls, event=event) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/event_handlers.py", line 264, in _handle_crud_like_event data = target_cls(**kwargs).api_retrieve() File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/djstripe/models.py", line 202, in api_retrieve return self.stripe_class.retrieve(id=self.stripe_id, api_key=api_key, expand=self.expand_fields) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/stripe/api_resources/abstract/api_resource.py", line 13, in retrieve instance.refresh() File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/stripe/api_resources/abstract/api_resource.py", line 17, in refresh self.refresh_from(self.request('get', self.instance_url())) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/stripe/stripe_object.py", line 207, in request response, api_key = requestor.request(method, url, params, headers) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/stripe/api_requestor.py", line 153, in request resp = self.interpret_response(rbody, rcode, rheaders) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/stripe/api_requestor.py", line 365, in interpret_response self.handle_error_response(rbody, rcode, resp.data, rheaders) File "/home/henry/Documents/Sites/Development/authenticjobs/env/lib/python3.6/site-packages/stripe/api_requestor.py", line 178, in handle_error_response raise err stripe.error.InvalidRequestError: Request req_7pF2asxJ89UmoZ: No such product: … -
How to setup AdminLTE-2.4.5 theme + CRUD in Django App?
The issue is: I want to set up "AdminLTE-2.4.5" theme+CRUD in Django2 App at frontside, I get many answers like direct cmd through installing it and I do it but I don't know how to set up for the view Please give solution step by step or any other solution regarding how to install AdminLTE-2.4.5 theme and show in front side ? Thanks -
CORS error using localhost but not using domain
I'm developing a react web app which communicates with a DRF backend via axios. While developing locally, I handled CORS by installing django-cors-headers and adding localhost:3000 to CORS_ORIGIN_WHITELIST (3000 is the default port for react w/ create-react-app): CORS_ORIGIN_WHITELIST = ( 'localhost:3000', ) This worked fine until I deployed to a remote server, when I suddenly started seeing CORS errors again: Access to XMLHttpRequest at 'http://localhost:8000/api/path/' from origin 'http://example.com:3000' has been blocked by CORS policy... which was baffling to me, since it already worked when I was developing locally. This had me stumped for hours until sheer frustration led me to change the react request from axios.post(localhost:8000/api/path/, { key1: val1, key2: val2, ... }) .then(response => { doSomeStuff(response); }); to axios.post(example.com:8000/api/path/, { key1: val1, key2: val2, ... }) .then(response => { doSomeStuff(response); }); and the whitelist from CORS_ORIGIN_WHITELIST = ( 'localhost:3000', ) to CORS_ORIGIN_WHITELIST = ( 'example.com:3000', ) At which point the CORS errors stopped. My question is: why did this happen? My understanding was that localhost and example.com were two names for the same server, but every other combination of whitelisting localhost/example.com and requesting localhost/example.com results in an error. What is the difference from a CORS perspective? -
how to get reverse relation in django serializers SlugRelatedField
I have two models ProductTypeModel and ProductModel, product_type is the foreign key in the product. Then I wrote a ModelSerializer for a product to get all the entries of ProductModel and along with some additional info. Now I'm unable to get product_sub_type from the ProductTypeModel in ProductSerializer I have tried SlugRelatedField in serializers, tried to set slug_field=product_sub_type and slug_field=product_type__product_sub_type and slug_field=product_type.product_sub_type models.py class ProductType(models.Model): """Product type model.""" id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) hsn = models.ForeignKey(HSN, related_name='product_types', on_delete=models.SET_NULL, null=True, blank=True) product_type = models.CharField(max_length=255, null=True, blank=True) product_sub_type = models.CharField(max_length=255, db_index=True) description = models.CharField(max_length=255, null=True, blank=True) # !TextFiled? def __str__(self): return str(self.product_type) def get_sub_type(self): return str(self.product_sub_type) class Meta: db_table = 'ProductTypes' unique_together = ('product_type', 'product_sub_type') class Product(models.Model): """Products model.""" product_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) product_type = models.ForeignKey( ProductType, related_name='related_products', on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=255, db_index=True) code_name = models.CharField(max_length=255, null=True, blank=True) href = models.CharField(max_length=500, blank=True, null=True) full_name = models.CharField(max_length=255, null=True, blank=True, db_index=True) manufacturer = models.ForeignKey( Manufacturer, related_name='manufactured_products', on_delete=models.SET_NULL, null=True, blank=True) packing = models.CharField(max_length=255, null=True, blank=True) packing_detail = models.CharField(max_length=255, null=True, blank=True) mrp = models.DecimalField( max_digits=8, decimal_places=2, null=True, blank=True) created_at = models.DateTimeField('created at', db_index=True, default=timezone.now) # !auto_add_now? def __str__(self): return str(self.full_name) class Meta: db_table = 'Products' unique_together = ('code_name', 'product_type') serializers.py class ProductTypeSerializer(serializers.ModelSerializer): # Serialize/Deserialize … -
django.db.connection don't support fileno() method
I have a custom method on my model manager that allows me to listen for notifications from modifications on the DB using postgreSQL. A short version of this code looks like this: def listen_for_notify(self): import select import psycopg2 import psycopg2.extensions from django.conf import settings db_data = settings.DATABASES['default'] listened = None returned_empty = None search_timeout = 15 conn = psycopg2.connect(dbname=db_data['NAME'], user=db_data['USER'], password=db_data['PASSWORD'], host=db_data['HOST'], port=db_data['PORT']) conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) curs = conn.cursor() curs.execute("LISTEN default;") timeout = timezone.now() + timezone.timedelta(0, search_timeout) while timezone.now() < timeout: time_diff = timeout - timezone.now() if select.select([conn], [], [], float(time_diff.seconds)) == ([], [], []): listened = False timeout = timezone.now() else: conn.poll() while conn.notifies: notify = conn.notifies.pop(0) if notify.payload == "notified": listened = True returned_empty = False timeout = timezone.now() if notify.payload == 'search request returned empty': listened = True returned_empty = True timeout = timezone.now() curs.close() conn.close() return listened, returned_empty It would be really nice if instead of using the psycopg2 library, I could use only django.db. Something like this: def listen_for_notify(self): from django.db import connection as conn listened = None returned_empty = None search_timeout = 15 with conn.cursor() as curs timeout = timezone.now() + timezone.timedelta(0, search_timeout) while timezone.now() < timeout: time_diff = timeout - timezone.now() if select.select([conn], [], [], …