Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to specify a "master" or "index" migration?
I'm working on an existing Django 2.2 application comprising a custom app in conjunction with a Wagtail CMS, where I'm iteratively adding new wagtail page-types in separate user stories over time. I want to be able to create a "master" or "index" migration that pre-builds each page-type in the database automatically when migrations are run (ours are performed in an Ansible task upon deployment). As far as I can tell, what I need requires: The auto-built migration that modifies the DB schema for each page A further migration that is always run last and which contains a dependencies attr - able to be updated with a single list-entry representing the new page's migration name, each time one is added. I can already auto-build page-types using the following logic in a create() method called from migrations.RunPython() but at the moment, this same page-build logic needs to exist in each page's migration - I'd prefer it if this existed in a single migration (or an alternative procedure if one exists in DJango) that can always be run. Ideally, the page_types list below could be replaced by just iterating over BasePage.__subclasses__(), (Where all page-types inherit from BasePage) meaning this "master" migration need never … -
How to make a read-only field in a Django formset
I've looked at a few other posts but they don't seem to work for me. I am trying to make one of my form fields to be read only but I can't get it to work. Here is my code. Also it isn't working perfectly when the form is posted, but it saves all the correct objects to the database. Gives the error 'list' object has no attribute 'dict' if you have any advice with that too. forms.py class OrderProductForm(forms.ModelForm): class Meta: model = OrderProduct fields = ('product', 'current_stock') def __init__(self, *args, **kwargs): super(OrderProductForm, self).__init__(*args, **kwargs) if self.instance.id: self.fields['product'].widget.attrs['readonly'] = True OrderProductFormSet = modelformset_factory(OrderProduct, extra=4, form=OrderProductForm) views.py class OrderProductCreateView(CreateView): model = OrderProduct form_class = OrderProductForm template_name = 'create_order_product.html' success_url = '/' def get_context_data(self, **kwargs): context = super(OrderProductCreateView, self).get_context_data(**kwargs) context['formset'] = OrderProductFormSet(queryset=OrderProduct.objects.none(), initial=[{'product': x} for x in Product.objects.all()]) return context def post(self, request, *args, **kwargs): formset = OrderProductFormSet(request.POST) if formset.is_valid(): return self.form_valid(formset) def form_valid(self, form): date = timezone.now() order = Order.objects.create(date=date) for item in form.cleaned_data: if item: order_product = OrderProduct(product=item.get('product'), current_stock=item.get('current_stock')) order_product.save() if order_product.order_amount() > 0: order.products.add(order_product) return super(OrderProductCreateView, self).form_valid(form) -
Django: Remove Exif data from Images in ImageField
There seem to be multiple variants of this question of how to strip exif data in django imagefields. None of the answers seem great. Many of them involve re-saving the image with PIL, at the risk of potentially breaking it. Others suggest using things like gexiv2... Given how important stripping exif is from image data for privacy is there any simple way to remove exif data from a user uploaded image? Perhaps this isn't even worth doing, since maybe it's less common of a precaution than I thought? -
i want to make two filters using django-filter. one from and to, and the second with a checkbox
this my model class yarn(models.Model): title = models.CharField('Название', max_length=150) description = models.TextField("Описание") price = models.PositiveSmallIntegerField("Цена", default=0) numberInStock = models.PositiveSmallIntegerField("Количество в наличии", default=0) color = models.ManyToManyField(Color, verbose_name="Цвет") creator = models.CharField("Производитель", max_length=150) img = models.ImageField("Изображение", upload_to="img/") url = models.SlugField(max_length=150, unique=True) matirial = models.ManyToManyField(Matirial, verbose_name="Материал") metrag = models.CharField('Метраж', max_length=150) my views class YarnView(ListView): model = yarn queryset = yarn.objects.all() template_name = "yarn/katalog.html" I want to sort by price and metrag first filter `<label>from: <input class="input__price" type="text" placeholder="0"> </label> <label>to: <input class="input__price" type="text" placeholder="0"> </label>` second filter some value<input class="float-right plus__menu" type="checkbox"> some value<input class="float-right plus__menu" type="checkbox"> some value<input class="float-right plus__menu" type="checkbox"> after reading the documentation, I realized what I need to create filter.py and create fields. for filter from and to price = django_filters.NumberFilter() price__gt = django_filters.NumberFilter(field_name='price', lookup_expr='gt') price__lt = django_filters.NumberFilter(field_name='price', lookup_expr='lt') for checkbox one = models.BooleanField() two = models.BooleanField() three = models.BooleanField() what's next -
ValueError at / dictionary update sequence element #0 has length 1; 2 is required
I have an issue i encounter while trying to run my urls & views in my Django project. It seems like that one way solves it but the other way (that suppose to work too, doesn't). I wonder why, maybe i am missing something here. So, the first way I defined my urls path's and views: project urls.py from django.contrib import admin from django.urls import include, path from django.conf.urls import url urlpatterns = [ path('admin/', admin.site.urls), path('Weekly_Program/', include('Weekly_Program.urls')), Weekly_Program urls.py from django.urls import path from . import views from django.conf.urls import url urlpatterns = [ path('', views.index, 'name=index'), Weekly_Program views.py from django.http import HttpResponse def index(request): return HttpResponse("<h1>This is the Weekly Program Homepage") The result of trying to run it once i try to conncet http://127.0.0.1:8000/Weekly_Program or even http://127.0.0.1:8000/admin is "Error page" that says: ValueError at / dictionary update sequence element #0 has length 1; 2 is required Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1 Exception Type: ValueError Exception Value: dictionary update sequence element #0 has length 1; 2 is required Exception Location: C:\Users\shai.QIL\PycharmProjects\Pulmonary_Rehab_Website\venv\lib\site-packages\django\urls\resolvers.py, line 358, in resolve Python Executable: C:\Users\shai.QIL\PycharmProjects\Pulmonary_Rehab_Website\venv\Scripts\python.exe Python Version: 3.8.5 Python Path: ['C:\\Users\\shai.QIL\\PycharmProjects\\Pulmonary_Rehab_Website', 'C:\\Users\\shai.QIL\\PycharmProjects\\Pulmonary_Rehab_Website', 'C:\\Program Files\\JetBrains\\PyCharm ' '2020.2\\plugins\\python\\helpers\\pycharm_display', 'C:\\Users\\shai.QIL\\Python\\Python38-32\\python38.zip', 'C:\\Users\\shai.QIL\\Python\\Python38-32\\DLLs', 'C:\\Users\\shai.QIL\\Python\\Python38-32\\lib', 'C:\\Users\\shai.QIL\\Python\\Python38-32', 'C:\\Users\\shai.QIL\\PycharmProjects\\Pulmonary_Rehab_Website\\venv', 'C:\\Users\\shai.QIL\\PycharmProjects\\Pulmonary_Rehab_Website\\venv\\lib\\site-packages', … -
How to create class based views in Django with nested crud?
I was able to refactor half of my code to Class Based Views, but I am having a hard time with the nested crud portion of it. Here are my code. I am trying to refactor all the reviews to Class Views. I am new to this. Any advice would be helpful. Thank you. I have two models here. One is for Beer and the other is Review. A beer has many reviews so when I go to Beer_List, I am able to access all the reviews for that beer. I just don't know how to refactor the review into class based views. from .models import Beer, Review from .forms import BeerForm, ReviewForm from django.shortcuts import render, redirect def get_beer(beer_id): return Beer.objects.get(id=beer_id) def beer_list(request): beers = Beer.objects.all() return render (request, 'beers/beer_list.html', {'beers': beers}) def new_beer(request): if request.method=="POST": form = BeerForm(request.POST or None) if form.is_valid(): beer = form.save(commit=False) beer.save() return redirect('beer_detail', beer_id=beer.id) else: form = BeerForm() return render(request, 'beers/beer_form.html', {'form': form, "type_of_reqeust": "New"}) def beer_detail(request, beer_id): beer = get_beer(beer_id) return render (request, 'beers/beer_detail.html', {'beer': beer}) def edit_beer(request, beer_id): beer = get_beer(beer_id) form = BeerForm(request.POST or None, instance=beer) if form.is_valid(): form.save() return redirect('beer_list') return render(request, 'beers/beer_form.html', {'form': form, 'type_of_reqeust': 'Edit'}) def delete_beer(request, … -
Django Queryset get value
I am trying to get the formatted datetime from the database, e.g. 2020-07-28 (stored this way in the DB). If I pass the below to the template: hello1 = Orders.objects.all()[:1].values('created') it returns <QuerySet [{'created': datetime.date(2020, 7, 28)}]> I just need it to return the value in the view (not the template). Any help is appreciated -
When testing Django REST Framework, why can't I get APIClient.credentials() to authenticate using a token?
I'm writing a functional (not unit) test against a basic API, like so: from decouple import config from rest_framework.test import APIClient, APITestCase class ObjectAPIResponseTest(APITestCase): base_url = 'http://localhost:8000/api/objects/' token = config('LOCAL_API_TOKEN') # token stored in local .env file authenticated_client = APIClient() def setUp(self): self.authenticated_client.credentials(HTTP_AUTHORIZATION='Token ' + self.token) def test_list_object_reaches_api(self): real_response = self.authenticated_client.get(self.base_url) self.assertEqual(real_response.status_code, 200) self.assertEqual(real_response.headers['content-type'], 'application/json') The test fails: AssertionError: 401 != 200 After successfully testing the request with curl, I decided to try to load up requests with the Authorization header instead of using Django REST Framework's APIClient: import requests from decouple import config from rest_framework.test import APIClient, APITestCase class ObjectAPIResponseTest(APITestCase): base_url = 'http://localhost:8000/api/objects/' token = config('LOCAL_API_TOKEN') # token stored in local .env file authentication_header = { 'Authorization': 'Token ' + token } def test_list_object_reaches_api(self): real_response = requests.get(self.base_url, headers=self.authentication_header) self.assertEqual(real_response.status_code, 200) self.assertEqual(real_response.headers['content-type'], 'application/json') This passes, which makes me wonder if I'm somehow using APIClient.credentials() incorrectly, although what I've done seems basically in line with the documentation. Any ideas what I'm doing wrong? -
Adding placeholder to form field in Django
So I've seen a number of different ways to do this but none that fit how I'm set up. I would like to add placeholder for the text fields in my form ('user', 'title', 'comment') forms.py class RestroomForm(forms.ModelForm): class Meta: model = RestroomReview fields = ( 'user', 'public', 'rest_type', 'baby', 'needle', 'handicap', 'rating', 'title', 'comment' ) models.py class RestroomReview(models.Model): ... ... ... venue = models.ForeignKey(Venue, blank=False, on_delete=models.CASCADE) user = models.CharField(max_length=200, blank=False) public = models.BooleanField(blank=False) rest_type = models.CharField( max_length=1, choices=RESTROOM_TYPE_CHOICES, default=MEN ) baby = models.BooleanField('Changing Table') needle = models.BooleanField('Sharps Container') handicap = models.BooleanField('Handicap Accessible') rating = models.IntegerField(choices=RATING_CHOICES, default=1) title = models.CharField(max_length=200, blank=False) comment = models.TextField(max_length=1000, blank=False) posted_date = models.DateTimeField(blank=False) def publish(self): posted_date = datetime.datetime.today() self.save() def __str__(self): return f'Review for {self.venue.name} by {self.user}' venue_detail.html <!-- form to review restroom --> <div class="container"> <form method="POST" action="{% url 'venue_detail' venue_pk=venue.pk %}"> {% csrf_token %} {% for field in restroom_form %} <div class="form-group"> <label for="{{ field.id_for_label }}">{{ field.label }}</label><br> {{ field|add_class:'form-control' }} </div> {% endfor %} <input type="submit" value="Submit"> </form> </div> Is there a way to set the placeholder in models.py? I'm having trouble setting it in forms.py like I've seen suggested on here. Or is there a place I can add it in … -
How to minus product-quantity after order process in Django?
I want to manage the quantity of the Product model. After the order process quantity should automatically minus from the original product quantity. How I can achieve this? I need proper help. Thanks in advance. Here is my Views: Cart View: def cart(request): if request.user.is_authenticated: user = request.user order, created = Order.objects.get_or_create(user=user, complete=False) items = order.orderitem_set.all() orderItems = order.get_cart_items else: items = [] order = {'get_cart_total': 0, 'get_cart_items': 0} orderItems = order['get_cart_items'] context = { 'items': items, 'order': order, 'orderItems': orderItems } return render(request, 'gui/cart.html', context) CheckOut View: def checkout(request): if request.user.is_authenticated: user = request.user order, created = Order.objects.get_or_create(user=user, complete=False) items = order.orderitem_set.all() else: items = [] order = {'get_cart_total': 0, 'get_cart_items': 0} # product_detail = Product.objects.get(id=pk) context = { 'items': items, 'order': order } return render(request, "gui/checkout.html", context) Update item View: def updateItem(request): print("view test") data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action: ', action) print('ProductId: ', productId) user = request.user product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(user=user, complete=False) total = order.get_cart_total order_item, created = OrderItem.objects.get_or_create( order=order, product=product, user=user, price=product.get_price) if action == 'add': order_item.quantity = (order_item.quantity + 1) # return redirect('cart') elif action == 'remove': order_item.quantity = (order_item.quantity - 1) if action == 'delete': order_item.quantity = … -
How to configure URLs within an existing site to direct to certain URLs within a WSGI application using apache?
I have a website that is built using static HTML and CSS being served by Apache at a URL, say www.example.com. On my server, I am also serving several other websites all of which are configured by .htaccess files. I have decided that I would like to add some functionality to my www.example.com website and have written a django application that I would like to include under this domain as part of the website to add functionality. The ultimate goal is to move more of this website over to Django but for now, the django application will only handle 2 functions, collecting feedback - which I'd like to live at www.example.com/feedback - and listing reviews - which I'd like to live at www.example.com/reviews and this has a subpage www.example.reviews/add. But the thing about these 2 features is that they are unrelated to each other and so it does not make sense to have them both under the same URL such as www.example.com/django/feedback(reviews) - I am trying to avoid this or avoid having to split my django application into 2 different applications each with its own wsgi entry point. Because all the individual configs are done with .htaccess files, my main … -
Django-channels: AttributeError: 'str' object has no attribute 'profile'
So I have my websockets in consumers, I did in consumers that when the websocket is receive it will update with +1 a FloatField in my models, the problem is that I dont know why is not working, here is my code: models.py: from django.contrib.auth.models import User from django.db import models from django.conf import settings from django.utils.translation import gettext_lazy as _ class ProfileImage(models.Model): """ Profile model """ user = models.OneToOneField( verbose_name=_('User'), to=settings.AUTH_USER_MODEL, related_name='profile', on_delete=models.CASCADE ) avatar = models.ImageField(upload_to='profile_image') notifications = models.FloatField(default='0') consumers.py: async def websocket_receive(self, event): # when a message is received from the websocket print("receive", event) # update the message notification badge val other_user = self.scope['url_route']['kwargs']['username'] notification = other_user.profile.objects.get(pk=1) notification.notifications = +1 notification.save() the problem is that when a websocket is receive it doesn´t update the floatfield value and it give me this error: notification = other_user.profile.objects.get(pk=1) AttributeError: 'str' object has no attribute 'profile' does anybody know what the problem is? -
Django: display a preview of an object's attribute - Class based views
Using a ListView Class-based-view, I am looping over the objects present in the database of a certain model in my HTML template, and, for instance, I can access an object's "body_text" attribute with the following syntax: {{object.body_text}} What if I wanted to only show the first 20 characters of that "body_text" attribute in my HTML template? How can I set that? -
Django extending model post_save
triyng to extened my model with post_save: class Profile(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE) def create_account_profile(sender, **kwargs): if kwargs['created']: account_profile = Account.objects.create(account=kwargs['instance']) post_save.connect(create_account_profile, sender=Account) getting the following error: Account() got an unexpected keyword argument 'account' -
django admin nested inline in another inline
I have models The logic is this: collection = bests restaurant = place collections include information about several restaurants there are collections, several restaurants can be linked to each selection (BestsPlace model) each collection has its own additional fields (BestsDetail model) each restaurant from the collection can have text added to additional collection fields (model BestsPlaceDetail) models.py class BestsPlace(BaseModel): bests = models.ForeignKey( Bests, on_delete=models.CASCADE, related_name='bests_place' ) place = models.ForeignKey( Place, on_delete=models.CASCADE, related_name='place_bests', ) class BestsDetail(BaseModel): bests = models.ForeignKey( Bests, on_delete=models.CASCADE, related_name='bests_detail', ) name = models.CharField(max_length=255) class BestsPlaceDetail(BaseModel): detail = models.ForeignKey( BestsDetail, on_delete=models.CASCADE, related_name='bests_place_detail', ) place = models.ForeignKey( Place, on_delete=models.CASCADE, related_name='place_bests_detail', blank=True, null=True, ) value = models.TextField(blank=True, null=True) admin.py class BestsPlaceInline(admin.TabularInline): model = models.BestsPlace class BestsDetailInline(admin.TabularInline): model = models.BestsDetail class BestsAdmin(admin.ModelAdmin): inlines = [BestsPlaceInline, BestsDetailInline] When adding a restaurant to a selection (BestsPlaceInline), I need to somehow add text to additional collection fields from the BestsPlaceDetail model. I would be grateful for a detailed answer with an example of implementation. -
Django can't load media image if DEBUG = False (WARNING:django.request:Not Found: /media/cache/)
User uploaded media images are not loading unless I have DEBUG set to True in my settings file. I'm getting the following error in my logs: WARNING:django.request:Not Found: /media/cache/ae/d2/aed2b5f7dcd26e01a2a9721540ee6e8e.jpg That exact folder path does exist locally and that image file does exist. I'm pretty lost what to do from here. I read all the other answers with similar questions and tried everything. If I set DEBUG = True, the images load just fine in both local dev and Heroku environments. Once DEBUG = False, the images don't load in either environment. Here's my code: settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) #STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.StaticFilesStorage' STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py urlpatterns = [ ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html template: {% load static %} {% load thumbnail %} {% thumbnail profile.profile_image "168x168" as im %} {{im.url}} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}" alt="profile image" class="avatar avatar-xl mb-4"> {% empty %} <img src="{% static 'assets/img/icons/theme/general/user.svg' %}" alt="Confirmation Icon" class="icon bg-primary" data-inject-svg="data-inject-svg"> {% endthumbnail %} im.url does produce the correct file path to the image. Any ideas? … -
Django honeypot error template customization
I am using Django honeypot (https://github.com/jamesturk/django-honeypot) and was wondering how to customize the honeypot_error.html page (https://github.com/jamesturk/django-honeypot/blob/master/honeypot/templates/honeypot/honeypot_error.html), which is executed when honeypot detection gets tripped. Thanks!! -
Django User-Specific objects via ForeignKey
I am trying to implement a user-specific Shopping Cart, which looks like: class Cart (models.Model): items = [] totalprice = 0 user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="cart", null=True) I have an HTML template that will display an Item and allow the current user to add it to their cart: <ul> <img src={{ item.pic.url }}> <li>{{ item.name }}</li> <li>{{ item.desc }}</li> <li>${{ item.cost }}</li> </ul> <br> <a href={% url 'gallery:add_to_cart' item.id %}>Add to Cart</a> The add_to_cart function is: def add_to_cart (request, id): if request.user.is_authenticated: if not request.user.cart.all(): c = Cart() c.save() request.user.cart.add(c) request.user.cart.all()[0].addItem(Item.objects.get(id=id)) return HttpResponseRedirect('/gallery/') Everything works fine for the first user, but once the first user logs out and another user logs in, their carts seem to be intertwined. Django will create a Cart for the second user, but this Cart will not initialize as empty; it will have the same contents as the Cart of the first user. Upon adding any item to the Cart as the second user, that item will be added to both Carts, and their contents will be identical. Active "Cart" objects upon adding an Item as the second user In short, I can't differentiate between individual users when accessing their Carts. Is there something I … -
How to call a python function inside html template in django
I want to call a python function and execute it in html template of django. The template : <li class="word-bot-sent"><p>Do you want some recommendations today? </p></li> {% for obj in Recommendation %} {% if obj.user == request.user %} <li class="word-bot-sent"><p>{{ obj.title }}</p></li> <li class="word-bot-sent"><p>{{ obj.text }}</p></li> {%endif%} {% empty %} {% endfor %} i want to execute the function here So what to do. Could someone help please. Thanks so much -
Access other sites through Django
I am working on a vps server and i am runing django on iis server. I have a view which receive a link from user and crawl the website and return some information to user. I have a module which handle request stuffs and just import that in my view which i call it with the user link. I also check the request module directly, and it works fine. The problem is that when i try the procedure through django view as a user i got the following error: ProxyError at /gathering HTTPConnectionPool(host='127.0.0.1', port=62341): Max retries exceeded with url: http://www.sid.ir/ (Caused by ProxyError('Cannot connect to proxy.', NewConnectionError('<urllib3.connection.HTTPConnection object at 0x0000021D6FF53EE0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))) From request module: html_doc = requests.get('http://www.sid.ir').text -
Django on Heroku and nginx
I have an Django app + Gunicorn on Heroku. Because Django doesn't serve media files on it's own I created nginx server on digitalocean. How should I configure nginx server to serve media files? As far as I know the connection between gunicorn and nginx implements through ports or sockets. I have no idea how to do this. django settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "blog/static/") STATICFILES_DIRS = [os.path.join(BASE_DIR, "static/"), os.path.join(BASE_DIR, "aboutpage/static/"), os.path.join(BASE_DIR, "blogpage/static/"), os.path.join(BASE_DIR, "contactspage/static/"), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_URL = "/" MEDIA_ROOT = os.path.join(BASE_DIR, "") nginx.conf file worker_processes 1; user nobody nogroup; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; accept_mutex off; } http { include mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log combined; sendfile on; upstream app_server { server unix:/root/blog/gunicorn.sock fail_timeout=0; } server { listen 80 default_server; return 444; } server { listen 80; client_max_body_size 4G; server_name example.com; keepalive_timeout 5; location /media/ { root /blog ; } location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } error_page 500 502 503 504 /500.html; location = /500.html { root /path/to/app/current/public; } } } Any idea is welcome! -
Undefined Variable 'os' pylint(undefined-variable) [57,18]
I am stuck here and dont know why this error is occuring.enter image description here -
Url is getting chopped when parameters are passed through url in django appilcation on cpanel of godaddy
deploying django application on cpanel of godaddy . whenever a function is accepting a parameter through url , apart of the url is getting chopped and getting the error,else when parameters are not passed it is working fine.but i want to pass parameters through url in django views on cpanel server -
Adding a success message to a generic redirect view in Django
I currently have a project where people can create posts. I want to display a message saying that a post has been Upvoted successfully however the SuccessMessageMixin isn't working. Ive tried other methods which is included in my code which I will post below. The SuccessMessageMixin works for other views. Im not sure why it isn't working for this View. Redirect View where code DOES NOT work class PostUpvoteRedirect(SuccessMessageMixin, RedirectView): model = Post success_message = "Post was upvoted successfully" def get_redirect_url(self, *args, **kwargs): obj = get_object_or_404( Post, publish__year=self.kwargs['year'], publish__month=self.kwargs['month'], publish__day=self.kwargs['day'], slug=self.kwargs['post'], ) url_ = obj.get_absolute_url() user = self.request.user if (user != None): if user in obj.Upvote.all(): obj.Upvote.remove(user) else: obj.Upvote.add(user) if user in obj.Downvote.all(): obj.Downvote.remove(user) success_message = "Post was upvoted successfully" return url_ Code where it DOES work class PostCreateView(SuccessMessageMixin, LoginRequiredMixin, CreateView): model = Post fields = ['title','body'] success_message = "Post was created successfully" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
('IM004', "[IM004] [unixODBC][Driver Manager]Driver's SQLAllocHandle on SQL_HANDLE_HENV failed (0) (SQLDriverConnect)")
I'm deploying a Django app with MSSQL to Azure app service using Docker containers and bumped into the above issue. ('IM004', "[IM004] [unixODBC][Driver Manager]Driver's SQLAllocHandle on SQL_HANDLE_HENV failed (0) (SQLDriverConnect)") When I finished building the image locally, I started it and everything works fine on localhost. However, after pushing it to the container registry (which will auto push to the app service), it doesn't work. I turned DEBUG mode to be True and got the above issue. I've looked around and all the questions asked seem to be irrelevant. Here's my docker setup RUN apt-get update && apt-get install -y ca-certificates \ && curl -k https://packages.microsoft.com/keys/microsoft.asc | apt-key add - \ && curl -k https://packages.microsoft.com/config/debian/10/prod.list > /etc/apt/sources.list.d/mssql-release.list \ && apt-get update \ && ACCEPT_EULA=Y apt-get -y install msodbcsql17 \ && ACCEPT_EULA=Y apt-get -y install mssql-tools \ && echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile \ && echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc \ && /bin/bash -c "source ~/.bashrc" \ && apt-get install -y unixodbc-dev \ && apt-get install -y libgssapi-krb5-2 Hope someone can help! Thanks a lot!