Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Matplotlib created a temporary config/cache directory
Matplotlib created a temporary config/cache directory at /var/www/.config/matplotlib because the default path (/tmp/matplotlib-b33qbx_v) is not a writable directory; it is highly recommended to set the MPLCONFIGDIR environment variable to a writable directory, in particular to speed up the import of Matplotlib and to better support multiprocessing. This is the message I'm getting in error.log file and 504 Gateway Time out error on browser . Someone please help to resolve this issue. -
Overwrite Submit button label in django crispy forms
I have an upload form which works fine. The idea is that someone uploads a file and chooses a title. The file gets saved to the server and can't be changed but the title can. So I'm looking for a way to reuse the same form and change the label on the submit button from "Upload File" to "Save Changes". This is my upload form: class MyForm(forms.Form): field_1 = forms.FileField() field_2 = forms.CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.layout = Layout( Row( Column('field_1', css_class='form-group col-md-12 mb-0') ), Row( Column('field_2', css_class='form-group col-md-12 mb-0') ), Submit('submit', 'Upload File', css_class='btn-success', formnovalidate='formnovalidate')) Now I want to create an "edit-variation" of the same form. The File field is changed to a CharField and made read only. It shows the server path of the file and can't be changed. Now I'm trying to change the button label. class MySecondForm(MyForm): field_1 = forms.CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['field_1'].widget.attrs['readonly'] = True self.helper['submit'].label = "Save Changes" The above does not show an error but does not work. The label remains "Upload File". I could of course just copy and change my FormHelper layout but my actual form has over 20 … -
Django url path render issue,
I got a failure on url path issue when try to do an exercise with Django " raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: URL route 'post/Title:Title/' uses invalid converter 'Title'. " 1.I've tried change the variable Title to other path name but still no working. 2.I check the setting.py with eplease help me. urls.py from django.contrib import admin from django.urls import path from mblog.views import homepage, showpost urlpatterns = [ path('admin/', admin.site.urls), path('', homepage), path('post/<Title:Title>/', showpost), ] views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Post from datetime import datetime # Create your views here. def homepage(request): posts = Post.objects.all() # SQL SELECT * FROM mblog_post(creat from models) now = datetime.now() return render(request, 'index.html', locals()) def showpost(request, Title): try: post = Post.objects.get(Title = Title) if post != None: return render(request, 'post.html', locals()) except: return redirect('/') setting.py import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'key is erase!!' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS … -
View your source map files produced using webpack
My application uses django on the backend and Vuejs on the frontend (doesn't use vue-cli). So the index.js from Vue is used something like this in my base.html {% compress js %} <script type="module" src="{% static 'path/to/index.js' %}"></script> {% endcompress %} Producing this -> index.4b6f970ead9c.js -> A compressed file in static/CACHE/js I need to build source-maps as .map files which in the end will be uploaded to sentry. Following is in my webpack.config.js : devtool: 'source-map', output: { sourceMapFilename: '[file].map', } Doing this, I get a warning on my console : DevTools failed to load SourceMap: Could not load content for http://localhost:8000/static/CACHE/js/tmpy_nqoqkg.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE I should expect the .map file to be in static/CACHE/js right? I couldn't any file with a .map extension anywhere in my app. But in the end of this (index.4b6f970ead9c.js) compressed file that is loaded I do see a mapping : //# sourceMappingURL=tmpy_nqoqkg.js.map Is there any way I can physically save the .map file for my application and use it later? -
Python web django vs flask using matplotlib
I am using python 3, and I want to create a webpage that displays some box plots that I have created using matplotlib. It should have a comfortable UI that allows the users to select what plots they want to view. The goal is to allow them to watch a few graphs simultaneously - one next to another. Also, you should note that the data that is used for creating the plots is on a local Microsoft SQL Server. [I know there is a way in which a far client could access it, but I haven't really tried it yet] Do you think I should use Django or Flask for this purpose? Thank you! -
Django: Count and display amount of items in a person order
I am trying to display a count of how many products are in a persons order. How do I go about doing that? I want to display the total item count in a order_detail.html page. Below is my code for reference. models.py: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) order_id = models.CharField(max_length=20, default=increment_order_id, null=True, blank=True, editable=False) location = models.ForeignKey(Location, on_delete=models.CASCADE) route = models.ForeignKey(Route, on_delete=models.DO_NOTHING, null=True, blank=True) delivery_date = models.DateField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) discount = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.PROTECT, related_name='items', null=True) desc = models.CharField(max_length=500, null=True) # Item product = models.ForeignKey(Product, on_delete=models.PROTECT, null=True, related_name='order_items') price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) quantity = models.IntegerField(default=1, null=False) views.py: @method_decorator(login_required(login_url='account_login'), name='dispatch') class OrderListView(ListFilteredMixin, ListView): model = Order template_name = 'orders/order/list.html' filter_set = OrderFilter queryset = Order.objects.all() @login_required(login_url='account_login') def order_detail(request, order_id): order = get_object_or_404(Order, order_id=order_id) order_item = OrderItem.objects.filter(order=order) context = { 'order': order, 'order_item': order_item } return render(request, 'orders/order/detail.html', context) -
Django modelforms
i am new in Django and i could use some help. So i am trying to change the labels name in my project and it doesn't work i have tried in different ways and this is the last one: from django import forms from django.utils.translation import ugettext_lazy as _ from Upload_Page.models import Form_Data class Upload_Document(forms.ModelForm): class Meta: model= Form_Data fields =['title','author','document_type','keywords','abstract','authentication','site','comments','file_upload'] widgets = { 'title' : forms.TextInput(attrs={ 'class':'title_class', 'placeholder':'Insert title here', 'label':'Tit' }) } This are the models: # Create your models here. class Form_Data(models.Model): title=models.CharField(unique=True,max_length=100,blank=False) author=models.CharField(max_length=100) document_type=models.CharField(choices=DOCUMENT_TYPES,max_length=500,blank=False,default=None) keywords=models.CharField(max_length=500) abstract=models.TextField(null=True,blank=True) authentication=models.CharField(choices=DOCUMENT_AUTHENTICATION_LEVEL,unique=True,blank=False,default=None,max_length=500) site=models.URLField(unique=True,blank=True) comments=models.TextField(null=True,blank=True) file_upload=models.FileField(default=None) def __str__(self): return self.title class Authentication_Level(models.Model): title=models.ForeignKey('Form_Data',to_field='title', on_delete=models.CASCADE,related_name='title1') authentication=models.ForeignKey('Form_Data',to_field='authentication', on_delete=models.CASCADE, related_name="authenticationlevel") download_rights=models.CharField(max_length=500) def __str__(self): return self and this is my view: from django.shortcuts import render from django.views.generic import View from Upload_Page import models from django.core.files.storage import FileSystemStorage from Upload_Page.forms import Upload_Document from django.shortcuts import redirect def upload_doc(request): if request.method == 'POST': form = Upload_Document(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('home_page:homepageview') else: form = Upload_Document(auto_id=True,label_suffix='') return render(request, 'Upload_Page/upload_page.html', {'form':form}) Also i want to align the label in the head of the inputs fields, how can i do that? Thank you in advance -
How can I choose the type of view in Django Rest Framework
I can create my view in Django with : Function Base View Class Base View Generic Views & Mixins ViewSets Now is there any standard to tell us when should we use which? and why we have this much type at all? -
django insert values into checked object field
I have an Order model and in my Order model I currently have 2 orders and I'm rendering both orders in my HTML file. In the dashboard, every order has a checkbox and the table header has a select dropdown list where I can select usernames and insert them to the handle_by field. I want to check any order and then select usernames in the dropdown list and insert them into the handle_by field of checked order, but something seems to be wrong in my Html file. models.py class Order(models.Model): item = models.ManyToManyField('Item') name = models.CharField(max_length=30) address = models.CharField(max_length=100) handle_by = models.CharField(max_length = 100, null=True) views.py def order_list(request): if request.method=="POST": if request.POST.get('usernames') and request.POST.get('pk'): saveresults = Order.objects.get(id=request.POST.get('pk')) saveresults.handle = request.POST.get('usernames') saveresults.save() context = { 'users': User.objects.all() 'order': Order.objects.all() return render(request, "order_list.html", context) HTML <table class="table table-responsive"> <thead class="bg-secondary"> <tr> <th> ## select drop-down list <form method="POST" class="form-select"> {% csrf_token %} <select class="ddlselect" multiple style="width: 180px;" value="{{ Order.handle }}"> {% for handle in users %} <option value="{{handle}}">{{handle}}</option> {% endfor %} </form> </select> <input type="text" id="txtusers" style="width:180px;" readonly name="usernames"/> <input type="submit" style="width:180px;" value="Insert Records..."/></th> ### <th scope="col">Item</th> <th scope="col">Name</th> <th scope="col">Address</th> </tr> </thead> <tbody> {% for order in order %} <tr> ## … -
Trying to export data from database to excel in djnago
views.py def export(request): print('start') ourid = request.POST.getlist("terid") queryset = Case_Info.objects.filter(id__in=list(map(int, ourid))) Case_Detail = Case_Info_Resource() print(ourid) dataset = Case_Detail.export(queryset) # error in this line response = HttpResponse( dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="persons.xls"' print('end') return response Ajax Script $(document).ready(function () { $('#Download').click(function () { console.log("clicked!") var list = []; $("input:checkbox[name='checkbox']:checked").each(function () { list.push($(this).val()); }); $('#Download').attr('disabled', 'disabled'); $.ajax({ url: '/Account_Manager/Download/', type: 'POST', data: { 'terid': list, 'csrfmiddlewaretoken': '{{csrf_token}}', }, timeout: 30000, traditional: true, dataType: 'text', success: function () { alert("The best cricketers are: " + list.join(", ")); $('#Download').removeAttr('disabled'); } }); }); }); What I am trying to do is pass several ids from the front end to the back and then export data from the database accordingly. everything is working fine till this following line. dataset = Case_Detail.export(queryset) after this line, it again reaches to the beginning of the function that results in the blank list that results in an empty excel file -
How do i resolve django error 'page not found'?
Here are my code if you can help me to figure out the errors views.py from django.db.models import Count, Q from django.contrib import messages from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render, get_object_or_404, redirect, reverse from django.views.generic import View, ListView, DetailView, CreateView, UpdateView, DeleteView from .forms import CommentForm, PostForm from .models import Post, Author, PostView from marketing.forms import EmailSignupForm from marketing.models import Signup form = EmailSignupForm() def get_author(user): qs = Author.objects.filter(user=user) if qs.exists(): return qs[0] return None class SearchView(View): def get(self, request, *args, **kwargs): queryset = Post.objects.all() query = request.GET.get('q') if query: queryset = queryset.filter( Q(title__icontains=query) | Q(overview__icontains=query) ).distinct() context = { 'queryset': queryset } return render(request, 'search_results.html', context) def search(request): queryset = Post.objects.all() query = request.GET.get('q') if query: queryset = queryset.filter( Q(title__icontains=query) | Q(overview__icontains=query) ).distinct() context = { 'queryset': queryset } return render(request, 'search_results.html', context) def get_category_count(): queryset = Post \ .objects \ .values('categories__title') \ .annotate(Count('categories__title')) return queryset class IndexView(View): form = EmailSignupForm() def get(self, request, *args, **kwargs): featured = Post.objects.filter(featured=True) latest = Post.objects.order_by('-timestamp')[0:3] context = { 'object_list': featured, 'latest': latest, 'form': self.form } return render(request, 'index.html', context) def post(self, request, *args, **kwargs): email = request.POST.get("email") new_signup = Signup() new_signup.email = email new_signup.save() messages.info(request, "Successfully subscribed") return … -
Django primary key setting
I want to set primary key as the combination of two fields of the model. (please check attached) But in database, i'm afraid it doesn't work... is there anything i should do more?? thank you in advance -
optimizing DRF serializer by multiple queryset
I am new to django and django-rest-framwork and I have encountered a used case where I need to optimize an API endpoint and the problem I found is that there is a SerializerMethodField() which is causing multiple SQL queries. Now here is my dilemma, it seems that in the SerializerMethodField(), there is a queryset from another model using contenttypes with no relationship to the the model to be serialized (Please see sample code below). This would entail multiple queryset if I will try to integrate this to views.py so that it would not cause multiple SQL queries. Am I in the right direction? Is it possible to have multiple queryset on APIVIEW? Or is there a way how to properly implement this kind of scenario? As much as possible, the model should not be re-design as this is already on prod and I am only at the liberty to have changes on the serializers. Please see sample code scenario below. Thank you very much. serializers.py class ClassStatisticsSerializer(ModelBaseSerializer): total_sessions = serializers.IntegerField() activity_changes = serializers.SerializerMethodField() def get_activity_changes(self, instance): class_activity_content_type_id = ContentType.objects.get(model='classactivity').id queryset = AuditLog.objects.exclude(Q(change_message__isnull=True) | Q(change_message='{}')) queryset = queryset.filter(Q(object_repr__icontains='Batch {0},'.format(instance.batch_number)), content_type=class_activity_content_type_id, action_flag=2) date = self.context.get('date') if date: # create datetime from date, … -
Selected values stay in the form after submitting in Django
I wanted to save selection values in the form when searching results show, so I used this code, but it doesn’t work. Selected values won’t show after submitting. <option selected="true" disabled="disabled">Products (All)</option> {% for key,value in products_choices.items %} <option value="{{ key }}" {% if key == value.products %} selected {% endif %} > {{ value }} </option> -
Django admin : how can i send data from admin.py to Jquery
i want to send data from admin.py in render_change_view to jquery file(or any method can i use in verification) for ex: i have table ProfileUser linked to User table(default table Django ) in the table ProfileUser every user(in table User) have role and grade and i have table ticket , if the user grade is >4 so he can add ticket else if grave >1 and <3 so he can see in ticket form just 2 or 3 field this is just a simple example , but i need it in a big condition best regards -
Can't deploy Django + Heroku. at=error code=H10 desc="App crashed" method=GET path="/favicon.ico"
I'm having trouble deploying my first Django app to Heroku. It works well in development but I can't find (or understand) the issue in the log. I've checked multiple threads with the same H10 error but everyone seem to have a somehow different log and their solutions are not working on my end. Let me know if there is anything else aside from the following that I should include in order to understand what's going on. Full log: 2020-08-11T08:36:47.390320+00:00 app[web.1]: self.callable = self.load() 2020-08-11T08:36:47.390320+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-08-11T08:36:47.390321+00:00 app[web.1]: return self.load_wsgiapp() 2020-08-11T08:36:47.390321+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-08-11T08:36:47.390321+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-08-11T08:36:47.390321+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 358, in import_app 2020-08-11T08:36:47.390322+00:00 app[web.1]: mod = importlib.import_module(module) 2020-08-11T08:36:47.390322+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module 2020-08-11T08:36:47.390322+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-08-11T08:36:47.390323+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2020-08-11T08:36:47.390323+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load 2020-08-11T08:36:47.390323+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 941, in _find_and_load_unlocked 2020-08-11T08:36:47.390324+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed 2020-08-11T08:36:47.390324+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 994, in _gcd_import 2020-08-11T08:36:47.390324+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 971, in _find_and_load 2020-08-11T08:36:47.390325+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked 2020-08-11T08:36:47.390333+00:00 app[web.1]: ModuleNotFoundError: … -
Is there a way to include Django ModelForm in javascript file?
I need to include a Django ModelForm in a dynamically created element in JavaScript. class PostForm(ModelForm): class Meta: model = Post fields = ['body'] widgets = { 'body': forms.Textarea(attrs={'placeholder':'Compose your post here...', 'rows':3}) } I want to include the above form inside of the container div let container = document.createElement('div'); container.innnerHTML = "<div></div>"; Is there a way to achieve this? -
Order Django queryset by related field (with code-value)
Simplifying my model a lot, I have the following: class Player(models.Model): name = models.CharField(max_length=50) number = models.IntegerField() class Statistic(models.Model): ''' Known codes are: - goals - assists - red_cards ''' # Implicit ID player = models.ForeignKey( 'Player', on_delete=models.CASCADE, related_name='statistics') code = models.CharField(max_length=50) value = models.CharField(max_length=50, null=True) I'm using a code-value strategy to add different statistics in the future, without the need of adding new fields to the model. My question is: Is there any way to order the players by their goals scored, for example? -
Concatenate 2 images one on top of the other in Python
I have 2 images that i want merged together one on top of the other. The first image is a user uploaded restaurant Logo, the other is a QR code that i generate after the user uploads a restuarant Menu .pdf file (The qr code points to the URL of the menu file). How can i make it so that the Company logo is scaled correctly and above the newly made QR code. Ideally i would like to keep them separate and have a new function that renders them merged, with the logo above the QR code. This way the user can choose if they want the plain qr code or the one with the logo. Otherwise if that's not possible, to be able to generate the qr code with the logo permanently embedded. Making the QR code in Models.py class Menu(models.Model): name = models.CharField(max_length=50) restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE) menuFile = models.FileField(upload_to='menus') qr_code = models.ImageField(upload_to='qr_codes', blank=True) uploadDate = models.DateTimeField(auto_now_add=True) class Meta: unique_together = ('restaurant', 'name',) def __str__(self): return(self.name) def save(self, *args, **kwargs): qr = qrcode.QRCode( version=8, box_size = 10, border=5, ) link = f'w w w.XX.com/{self.name}' qr.add_data(link) qr.make(fit=True) img = qr.make_image(fill='black', back_color='white') fname = f'{self.name}QRCode.png' buffer = BytesIO() img.save(buffer, 'PNG') … -
How to covert set to String?
I have a model and i am returning the function using @property, but it's giving me data in set, and i want this data in string with comma, please let me know how i can do it. Here is my models.py file... class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address = models.CharField(max_length=200, null=True) city = models.CharField(max_length=200, null=True) state = models.CharField(max_length=200, null=True) zipcode = models.CharField(max_length=200, null=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address @property def Address(self): return str(self.address), str(self.state), str(self.zipcode) and here is my admin.py file, where is am calling the function... class ShippingAddressAdmin(admin.ModelAdmin): list_display=['city','state','Address'] readonly_fields=['city','Address'] admin.site.register(ShippingAddress, ShippingAddressAdmin) the output of @property function is this ('House number-69, sector-55, Gurugram', 'Haryana', '122002') -
Django DRF when file is empty while updating it gives error - when file is selected it works
Hi I have a view in DRF - when I select the image then it works fine but when no files are selected then it give an error The submitted data was not a file. Check the encoding type on the form.code invalid I have also tried conditionally putting the imagefield i.e. (mainimage and image_with_self) in the dat1 {}, but there also it does not work . It does not include the keyvalue pair in the dat1={} instead it put outside the dictonary object as old[Inmemoryuploaded:filename ] Below is my code class ArtworkViewSet(viewsets.ModelViewSet): queryset = Artwork.objects.all() # import pdb; pdb.set_trace(); serializer_class = ArtworkSerializer permission_classes = [AllowAny] def partial_update(self, request, *args, **kwargs): # import pdb; pdb.set_trace() # kwargs['partial'] = True partial = kwargs.pop('partial', True) instance = self.get_object() dat1={} if request.data.get('own_work') == "false": name_of_creator=request.data.get('name_of_creator') name_of_owner=request.data.get('name_of_owner') age_of_work=request.data.get('age_of_work') house_no=request.data.get('house_no') building_name=request.data.get('building_name') else: user_id=request.user.id userprofile = UserProfile.objects.get(user=user_id) name_of_creator=userprofile.name name_of_owner=userprofile.name house_no=userprofile.house_no building_name=userprofile.building_name # if(request.data['image_with_self']!= ""): # dat1['image_with_self']=request.data['image_with_self'] # if(request.data['mainimage'] != ""): # dat1['mainimage']=request.data['mainimage'] dat1={ 'title': request.data.get("title"), 'description': request.data.get("description"), 'artcontest': request.data.get("artcontest"), 'mainimage':request.data['mainimage'], 'image_with_self':request.data['image_with_self'], 'category_id': request.data.get("category"), 'size': request.data.get("size"), 'weight': request.data.get("weight"), 'material': request.data.get("material"), 'sale_lend': request.data.get("sale_lend"), 'own_work': request.data.get("own_work"), 'name_of_creator': name_of_creator, 'name_of_owner': name_of_owner, 'house_no': house_no, 'building_name': building_name, } # instance.save() import pdb; pdb.set_trace() serializer= self.get_serializer(instance, dat1, partial=partial) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) -
How to exit from a try/except inside of an if/else statement in Python
So I have this: if condition: ... elif condition2: ... elif condition3: try: existing_bid = # get some object from django models except SomeError: # if this object does not exist # here I need to escape from if/else to main scope if ... # some comparison with an existing_bid: #return error ... # try to manipulate existing_bid object and save it # here I need to escape ... ... What is the best practice to escape from try/except that is inside of an if/else to main scope? Thanks edit: provided some context -
How to return a function as a query result in graphene?
I have a post model, and I want to know if the currently logged in user has liked the post or not: Would something like this work or should I use a different request to know if the user has liked/not liked the post: class PostNode(DjangoObjectType): id = graphene.ID(source='pk', required=True) liked = graphene.Boolean(source=Like.objects.filter(user=info.context.user,post=Post.objects.get(pk=id))) class Meta: model = Post interfaces = (graphene.relay.Node,) (of course it doen't work) The query: query { posts { edges { node { liked title text } } } } The result: { "data": { "posts": { "edges": [ { "node": { "liked": false, "title": "hi", "text": "m" } }, { "node": { "liked": true, "title": "blalblala", "text": "blalalblala" } } ] } } } -
Heroku does not find DATABASE_URL
I am trying to deploy my Django application to Heroku and make separate configuration for local and heroku deployments. I currently have this: if 'DATABASE_URL' in os.environ: import dj_database_url DATABASES = { 'default': dj_database_url.config(conn_max_age=600) } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Method main basically creates an instance of Selenium (geckodriver) and scrapes something off a web page. However, if I try to run it locally using statement: heroku ps:exec And then running: python3 -c 'from scraper.common import main; main()' It prints: Table not found Because it was still using SQLite database. I then connected to dyno the same way and tried: python3 -c 'import os; os.environ' And the output is not showing DATABASE_URL variable. Can somebody please help me? -
Field required when another field is populated using constraints in Django Python
I'm attempting to implement account bans in Django Python. If ban is temporary, it requires an expiration date. If it's permanent, then the expiration date should be null. I've tried to do this with CheckConstraint, with no luck. It returns an integrity error as the constraint fails. def constraint__temporary_expires(ban_type, expires): return (ban_type == "T" and expires is None) and (ban_type != "P") class Ban(Moderation): # Moderation is a model BAN_CHOICES = [ ("P", "Permanent"), ("T", "Temporary") ] ban_type = models.CharField(choices=BAN_CHOICES, max_length=1, verbose_name="Type") expires = models.DateTimeField(null=True, blank=True, help_text="This is ignored if ban is permanent") class Meta: constraints = [ models.CheckConstraint( check=models.Q( ban_type=constraint__temporary_expires(models.F("ban_type"), models.F("expires")) ), name="temporary_expires" ) ]