Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save an image to FileField from its path?
I have an image stored in my media/logo/ folder and I'd like to save it to my model's FileField from my view. Here's what I tried but I'm getting an encoding error & the file becomes corrupted after I'm trying to save it. UnicodeDecodeError: 'charmap' codec can't decode byte ... views.py: def save_records(request): new_path = os.path.join(settings.MEDIA_ROOT, 'logo', filename) same_file = File(new_path, filename) Company.objects.create(logo=same_file) I have some trouble understanding how I can save the file in new_path to the FileField, any idea ? -
Django - CreateView /Modelform wont save Many to Many
I'm having trouble with the following problem: I am working on simple database app where users can add both Objects and create 'Notes' for these objects. These notes in turn can have tags (a many to many) which can be used to filter them. However, when I am creating a new Note, the accompanying tags are not saved in the form. Here is the code I used for the Noteform class NoteForm(ModelForm): class Meta: model = Note fields = ['content', 'tags'] def __init__(self, *args, **kwargs): self.model = kwargs.pop('model') self.app = kwargs.pop('app') self.key = kwargs.pop('model_pk') self.model_object = apps.get_model(self.app, self.model) self.linked_object = self.model_object.objects.get(pk=self.key) super(NoteForm, self).__init__(*args, **kwargs) def save(self, commit=True): note = super(NoteForm, self).save(commit=False) note.content_object = self.linked_object if commit: note.save() return note And here is the accompanying view: class BaseNoteCreateView(LoginRequiredMixin, CreateView): login_url = '/login/' form_class = NoteForm def get_form_kwargs(self): kwargs = super(BaseNoteCreateView, self).get_form_kwargs() kwargs['model'] = self.kwargs['model'] kwargs['app'] = self.kwargs['app'] kwargs['model_pk'] = self.kwargs['model_pk'] return kwargs def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) Now I read that I might have to use the save_m2m() method. However, whenever I include it into the form or the view I run into the 'NoteForm' object has no attribute 'save_m2m' error. When I print the 'kwargs' in the … -
Django Model Form does not display Image field properly and does not Post it
The look of the File Upload for the picture in the Form is not OK as the button is inside the field. While it shows in the form as uploaded, it won't post. When I look in the firebug, I can see that the field for the File image is not being sent through with the other name fields, so the form never validates. Here is how it looks enter image description here Here is the definition in the Model. picture = models.ImageField(upload_to=user_directory_path) So when Django creates the Form it does it in that weird way for the File filed How should I then define the Field for File in the Model? Or where is the error lying? -
Comparing two variables in Jinja2?
I'm trying to print some values from my db onto a html page. Here's my jinja2 code: {% for Event in seller_event_disp %} {% for Items in seller_event_items_disp %} {% if Items.event_id == event_id %} {{ Items.item_name }} {% endif %} {% endfor %} {% endfor %} seller_event_disp and seller_event_items_disp are objects that I passed onto the html form via views. event_id is a variable which is also passed in a similar way. Individually, I have checked all of these and they do print properly in the html. For example, {{ event_id }} displays 1 on the page {% for Event in seller_event_disp %} {% Event %} {% endfor %} displays 1234, and similarly iterating through seller_event_items works as well. This is why I'm wondering if the == comparison is the issue. Indeed adding it anywhere to the code makes the rest of it after the addition stop working. What am I doing wrong here? Thanks! -
IntegrityError at /accounts/regist_save/ happens
IntegrityError at /accounts/regist_save/ NOT NULL constraint failed: accounts_newuser.user_id error happens .I wrote in views.py def regist(request): regist_form = RegisterForm(request.POST or None) profile_form = ProfileForm(request.POST or None) context = { 'regist_form': regist_form, 'profile_form': profile_form, } return render(request, 'registration/regist.html', context) @require_POST def regist_save(request): regist_form = RegisterForm(request.POST or None) profile_form = ProfileForm(request.POST or None) if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid(): regist = regist_form.save(commit=False) regist.is_staff = True regist.save() profile = profile_form.save(commit=False) sex = request.POST.get("sex", "") print(1111) print(sex) profile.save() else: print(regist_form.errors) print(profile_form.errors) return redirect('detail') regist.html <div class="form-group-lg"> <label for="id_username">Username</label> {{ regist_form.username }} </div> <div class="form-group-lg"> <label for="id_email">Email</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label for="id_password">Password</label> {{ regist_form.password1 }} </div> <div class="form-group-lg"> <label for="id_password">Password2</label> {{ regist_form.password2 }} <p class="help-block">{{ regist_form.password2.help_text }}</p> </div> {% load static %} <div class="form-group-lg"> <label for="birthday">Date</label> <select id="year" class="form-control year" name="year"> <option value="">--</option> </select> Year <select id="month" class="form-control month" name="month"> <option value="">--</option> </select> Month <select id="day" class="form-control day" name="day"> <option value="">--</option> </select> Day <br> <br> </div> <div class="form-group-lg"> <label for="sex">SEX</label> <select id="sex" class="form-control sex" name="sex"> <option value="">--</option> <option value="male">male</option> <option value="female">female</option> </select> </div> <script src="{% static 'accounts/register.js' %}"></script> <button type="submit" class="btn-lg regist">REGIST</button> <input name="next" type="hidden" /> {% csrf_token %} </form> regist.js $(() => { for (let i = 1900; i … -
How to convert from unicode list to normal list in python/django
How can i convert this list: list = [u"[u'book1', u'book2', u'book3']"]into this list: [u'book1', u'book2', u'book3'] I tried this : n = ast.literal_eval(list) but i got this error: raise ValueError('malformed string') ValueError: malformed string what else can i do to change this list without "u" -
django combine to query result and perform query on the combined query result on postgres
I am trying to accomplish a query to determine the number of checkout and checkin in a day for an attendance that is unique to the employee without duplication of checkin and checkout, and picking the latest to be distinct. In essence is combine 2 query result, and perform a query on the result. Its much easier explained below. I have 2 models: class Employee(models.Model): fullname = models.CharField(max_length=30, blank=False) class Attendance(models.Model): CHECKIN = 1 CHECKOUT = 2 ATTENDANCE_TYPE_CHOICES = ( (CHECKIN, "Check In"), (CHECKOUT, "Check Out"), ) employee = models.ForeignKey(Employee) activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN) timestamp = models.DateTimeField(auto_now_add=True) And I have this 2 queries to obtain the unique CheckIn and CheckOut of the employee in the attendance. unique_employee_attendance_checkin_today = Attendance.objects.filter(company=auth_employee.employee.company.id, activity_type=Attendance.CHECKIN, timestamp__date = today).order_by( 'employee_id','-timestamp').distinct('employee_id') unique_employee_attendance_checkout_today = Attendance.objects.filter(company=auth_employee.employee.company.id, activity_type=Attendance.CHECKOUT, timestamp__date = today).order_by( 'employee_id','-timestamp').distinct('employee_id') Assuming I have these records Employee {"id":1, "employee":"michael jackson", "id":2, "fullname":"mariah carey", "id":3, "fullname":"taylor swift"} Attendance {"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08", "id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13", "id":3, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 11:30", "id":4, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13", "id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30", "id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13", "id":7, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 20:30", "id":8, … -
Elastic Beanstalk with Django: is there a way to run manage.py shell and have access to environment variables?
Similar question was asked here, however the solution does not give the shell access to the same environment as the deployment. If I inspect os.environ from within the shell, none of the environment variables appear. Is there a way to run the manage.py shell with the environment? PS: As a little side question, I know the mantra for EBS is to stop using eb ssh, but then how would you run one-off management scripts (that you don't want to run on every deploy)? -
How to use token authentication while testing REST API
I am trying to use test the API request by using tokens. I was able to extract the token but I struggle to find a way to use it. This is how I get my token: @pytest.mark.django_db class TestUserAPI(APITestCase): def setUp(self): self.created_user = UserFactory() User.objects.create_user(username='test', password='pass1234') def test_authentification(self): request = self.client.post('http://localhost:8000/api/v1/auth/', { "username": "test", "password": "pass1234" }) TestUserAPI.token = request.data["token"] assert request.status_code == 200 and this is how I use it: def test_profile(self): request = self.client.get('http://localhost:8000/api/v1/profile/', TokenAuthentication = 'token {}'.format(TestUserAPI.token)) assert request.status_code == status.HTTP_200_OK It gives me 401 error. What is the correct way of using token? -
How to update an ImageField in Django
I am making a website and would like to make it possible for each user to upload and update his own profile picture. The update-profile template loads perfectly fine. I can update all the other fields, except for the image field. It can only be updated from the /admin page, but not from the update-profile page. This is my image field in the Profile model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) dob = models.DateField(default=datetime.date(1989, 12, 25)) gender = models.CharField(max_length=12, choices=GENDER_CHOICES, default='Unspecified') city = models.CharField(max_length=100, default='Braşov') image = models.ImageField(upload_to='profilepics', blank=True) Here is my ProfileForm: class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('dob', 'gender', 'city', 'image') This is the html template: {% block body %} <form method="post"> <div class="container"> {% csrf_token %} {{ user_form.as_p }} {{ profile_form.as_p }} <button type="submit">Update</button> <a href="myprofile" class="btn btn-info" role="button">Cancel</a> </form> </div> {% endblock %} And this is the update_profile view: @login_required @transaction.atomic def update_profile(request): if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, ('Your profile was successfully updated!')) return redirect('myprofile') else: messages.error(request, ('Please correct the error below.')) else: user_form = UserForm(instance=request.user) profile_form = ProfileForm(instance=request.user.profile) return render(request, 'filter/updateprofile.html', { 'user_form': user_form, 'profile_form': profile_form }) … -
Serving static files with nginx on multiple machines and hard drives
I have one project what will store large media content after it will be deployment. Project use Python, Django, also runned via Gunicorn and Supervisor. For static files I will use nginx. Basic setup I made by following this article, but I have an question, how can I store content more dynamicly. At the start I have one machine with 4 hard drives for 2Tb each, later will be buyed more, as well as the new machines (currently I have only one). Site located as site.com, nginx located at subdomain i.site.com and have 2 folders in a root: /static for storing css, js, svg, e.t.c. design elements and /media what will be stored media content. The problem is setup nginx to write media on each hard drives and each machine will be used. For the speed I need to write every new file in a different hard drive (like rotation/loop), for example I saving file1, it writed at machine1/hdd1, then I saving file2, it writed at machine1/hdd2... file4 at machine1/hdd4, file5 at machine2/hdd1 (currently as I mentioned I have only one machine, but will be more in a future). So, anyone have expirience or idea how can I make that? … -
while doing Django project run server does not work?
python manage.py runserver Traceback (most recent call last): File "manage.py", line 17, in "Couldn't import Django. Are you sure it's installed and " ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? ---solve my problem -
How can I upgrate plan on Heroku from hobby-dev to hobby-basic?
I would like to upgrate plan on Heroku with my Django app from hobby-dev to hobby-basic? At the moment heroku pg:info returns: Plan: Hobby-dev Status: Available Connections: 0/20 PG Version: 9.6.4 Created: 2017-11-12 19:20 UTC Data Size: 135.9 MB Tables: 19 Rows: 1272760/10000 (Above limits, access disruption imminent) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql-cub... I tried to use this but I am not sure which way should I choose. It seems to be that pg:copy would be the best idea? I think that steps in this case should look as shown below, am I right? 1.heroku addons:create heroku-postgresql:standard-0 2.heroku pg:wait 3.heroku maintenance:on 4.heroku pg:copy DATABASE_URL HEROKU_POSTGRESQL_PINK --app sushi How can I check DATABASE_URL and HEROKU_POSTGRESQL_PINK? I quess that DATABASE_URL is in Config Vars and this is it postgres://gxapb...2840@ec2-77-131-196-1207.compute-1.amazonaws.com:5432/d...md, isn't it? But how can I generate HEROKU_POSTGRESQL_PINK? I found information that it is the target database. 5.heroku pg:promote HEROKU_POSTGRESQL_PINK 6.heroku maintenance:off -
Create a new Google Maps after Ajax success with Django
I have made a Google Maps with dive location in the Netherlands. The next step is that an user can search on the page for a dive location and that the search results are showing on the Google Maps. So it must replace the exisitng map. I'm a new to Django and never worked with Javascript before. The problem is that I don't know how to make a new map with dive locations that are getting back from the search result. Urls.py from django.conf.urls import url from . import views app_name = 'kaart' urlpatterns = [ # /gis url(r'^$', views.index, name='index'), # Voor ajax zoekfunctie url(r'^search/$', views.search_duik_locaties, name='search_duik_locaties'), # /gis/id_number/ url(r'^(?P<duik_id>[0-9]+)/$', views.detail, name='detail'), ] views.py from django.shortcuts import render, get_object_or_404 from .models import Duikplaats def index(request): all_duik_locaties = Duikplaats.objects.all() longitude = Duikplaats.objects.values('longitude') latitude = Duikplaats.objects.values('latitude') content = { 'all_duik_locaties': all_duik_locaties, 'longitude': longitude, 'latitude': latitude, } return render(request, 'kaart/index.html', content) def detail(request, duik_id): duikplaats = get_object_or_404(Duikplaats, pk=duik_id) return render(request, 'kaart/details.html', {'duikplaats': duikplaats}) def search_duik_locaties(request): query = request.GET.get('q') if query is not None and query != '' and request.is_ajax(): zoek_duik_locaties = Duikplaats.objects.filter(duik_locatie__icontains=query) lat = zoek_duik_locaties.values('latitude') con = { 'zoek_duik_locaties': zoek_duik_locaties, 'lat': lat } return render(request, 'kaart/ajax_search.html', con) return render(request, 'kaart/ajax_search.html') index.html (part … -
I have deployed my django project in pythonanywhere but it will get Unhandled Exception:
Error running WSGI application Improperly Configured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. -
Program does not read always regist_form.is_valid() & profile_form.is_valid()
Program does not read always regist_form.is_valid() & profile_form.is_valid() .I wrote in views.py def regist(request): regist_form = RegisterForm(request.POST or None) profile_form = ProfileForm(request.POST or None) context = { 'regist_form': regist_form, 'profile_form': profile_form, } return render(request, 'registration/regist.html', context) @require_POST def regist_save(request): regist_form = RegisterForm(request.POST or None) profile_form = ProfileForm(request.POST or None) print(request.POST) if request.method == "POST" and regist_form.is_valid() and profile_form.is_valid(): regist = regist_form.save(commit=False) regist.is_staff = True regist.save() profile = profile_form.save(commit=False) profile.user = user sex = request.POST.get("sex", "") print(1111) print(sex) profile.save() return redirect('detail') in regist.html <div class="form-group-lg"> <label for="id_username">Username</label> {{ regist_form.username }} </div> <div class="form-group-lg"> <label for="id_email">Email</label> {{ regist_form.email }} </div> <div class="form-group-lg"> <label for="id_password">Password</label> {{ regist_form.password1 }} </div> <div class="form-group-lg"> <label for="id_password">Password2</label> {{ regist_form.password2 }} <p class="help-block">{{ regist_form.password2.help_text }}</p> </div> {% load static %} <div class="form-group-lg"> <label for="birthday">Date</label> <select id="year" class="form-control year" name="year"> <option value="">--</option> </select> Year <select id="month" class="form-control month" name="month"> <option value="">--</option> </select> Month <select id="day" class="form-control day" name="day"> <option value="">--</option> </select> Day <br> <br> </div> <div class="form-group-lg"> <label for="sex">SEX</label> <select id="sex" class="form-control sex" name="sex"> <option value="">--</option> <option value="male">male</option> <option value="female">female</option> </select> </div> <script src="{% static 'accounts/register.js' %}"></script> <button type="submit" class="btn-lg regist">REGIST</button> <input name="next" type="hidden" /> {% csrf_token %} </form> in regist.js $(() => { for (let i = 1900; … -
payu india gateway integration in Django website
I am trying to integrate payu gateway in Django website. Code for utils.py. (generating hash) from hashlib import sha512 from django.conf import settings KEYS = ('key', 'txnid', 'amount', 'productinfo', 'firstname', 'email', 'udf1', 'udf2', 'udf3', 'udf4', 'udf5','udf6', 'udf7', 'udf8', 'udf9', 'udf10') def generate_hash(data): # keys = ('key', 'txnid', 'amount', 'productinfo', 'firstname', 'email', # 'udf1', 'udf2', 'udf3', 'udf4', 'udf5','udf6', 'udf7', 'udf8', 'udf9', 'udf10') hash = sha512(b'') for key in KEYS: hash.update(("%s%s" % (str(data.get(key, '')), '|')).encode()) # hash.update(('|||||').encode('utf8')) hash.update((settings.PAYU_INFO.get('merchant_salt')).encode('utf8')) return hash.hexdigest().lower() def verify_hash(data, SALT): keys.reverse() hash = sha512((settings.PAYU_INFO.get('merchant_salt')).encode('utf8')) hash.update(("%s%s" % ('|', str(data.get('status', '')))).encode('utf8')) # hash.update(('|||||').encode('utf8')) for key in KEYS: hash.update(("%s%s" % ('|', str(data.get(key, '')))).encode('utf8')) return (hash.hexdigest().lower() == data.get('hash')) Code for views.py for app: from django.conf import settings from django.shortcuts import render, render_to_response from django.http import HttpResponse, HttpRequest, Http404 from django.template import RequestContext from django.conf import settings from django.core.urlresolvers import reverse from payu.forms import PayUForm from cart.forms import OrderForm from payu.utils import generate_hash from django.utils import lorem_ipsum #from django.contrib.webdesign.lorem_ipsum import sentence as lorem_ipsum from uuid import uuid4 from random import randint import logging logger = logging.getLogger('django') def checkout(request): if request.method == 'POST': order_form = OrderForm(request.POST) if order_form.is_valid(): initial = order_form.cleaned_data initial.update({ 'key': settings.PAYU_INFO['merchant_key'], 'surl': request.build_absolute_uri(reverse('order.success')), 'furl': request.build_absolute_uri(reverse('order.success')), 'curl': request.build_absolute_uri(reverse('order.cancel')), 'hash': generate_hash(request.POST)}) # Once you … -
Django queryset NOT INTERSECT for 2 models using postgres
I have a Django app, and I am trying to find out Employee that was NOT in Attendance 2017-12-05. I am trying to find out a queryset to accomplish this. The following are the details of the model, records, and the outcome I am trying to accomplish. I have 2 models: class Employee(models.Model): fullname = models.CharField(max_length=30, blank=False) class Attendance(models.Model): CHECKIN = 1 CHECKOUT = 2 ATTENDANCE_TYPE_CHOICES = ( (CHECKIN, "Check In"), (CHECKOUT, "Check Out"), ) employee = models.ForeignKey(Employee) activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN) timestamp = models.DateTimeField(auto_now_add=True) Assuming I have the records below: Employee {"id":1, "employee":"michael jackson", "id":2, "fullname":"mariah carey", "id":3, "fullname":"taylor swift", "id":4, "fullname":"selena gomez"} Attendance {"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08", "id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13", "id":3, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13", "id":4, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13", "id":5, "employee": 3,"activity_type": 1, timestamp: "2017-12-06 08:08"} This is the intended output I am trying to accomplish: For the date 2017-12-05, this employee was not in attendance (meaning there was no record in Attendance for 2017-12-05) {"id":3, "fullname":"taylor swift", "id":4, "fullname":"selena gomez"} What is the queryset to list out the employee that is not in attendance on a particular date 2017-12-05 ? I believe its … -
error in migrate django when i use djangocms
i want to install django cms by hand according to this page i added these apps 'djangocms_file', 'djangocms_googlemap', 'djangocms_inherit', 'djangocms_picture', 'djangocms_teaser', 'djangocms_video', 'djangocms_link', 'djangocms_snippet', 'menus', 'easy_thumbnails' when i want to migrate returns me Traceback (most recent call last): File "manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute django.setup() File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/djangocms_inherit/models.py", line 11, in <module> class InheritPagePlaceholder(CMSPlugin): File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/djangocms_inherit/models.py", line 22, in InheritPagePlaceholder _("language"), max_length=5, choices=get_language_tuple(), blank=True, File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/cms/utils/i18n.py", line 79, in get_language_tuple return [(lang['code'], lang['name']) for lang in get_languages(site_id)] File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/cms/utils/i18n.py", line 24, in get_languages result = get_cms_setting('LANGUAGES').get(site_id) File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/cms/utils/conf.py", line 278, in get_cms_setting return COMPLEX[name]() File "/home/amg/Documents/Computer/Python/Django/vira/vira/lib/python3.6/site-packages/cms/utils/conf.py", line 233, in get_languages 'LANGUAGE_CODE "%s" must have a matching entry in LANGUAGES' % settings.LANGUAGE_CODE django.core.exceptions.ImproperlyConfigured: … -
Django - how do you decide which model to put foreign key?
Lets say I have two models that looks like this: class Album(models.Model): pub_date = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=250, blank=False, unique_for_date="pub_date") class Track(models.Model): title = models.CharField(max_length=250, blank=False, unique_for_date="pub_date") album = models.ForeignKey(Album) What is the difference between putting the ForeignKey (one-to-many) relationship on the Track model versus the Album model? How does one decide such a thing? -
Django Queryset get list for the day of a particular type, unique foreignkey id using Postgres database
I am trying to find a query to get a list of latest attendance for a particular day, with unique employee that has checked in (CHECKIN = 1) Below is my model, records and what I am trying to accomplish. My model has 2 models: class Employee(models.Model): fullname = models.CharField(max_length=30, blank=False) class Attendance(models.Model): CHECKIN = 1 CHECKOUT = 2 ATTENDANCE_TYPE_CHOICES = ( (CHECKIN, "Check In"), (CHECKOUT, "Check Out"), ) employee = models.ForeignKey(Employee) activity_type = models.IntegerField(choices = ATTENDANCE_TYPE_CHOICES, default=CHECKIN) timestamp = models.DateTimeField(auto_now_add=True) Assuming I have the records below: Employee {"id":1, "employee":"michael jackson", "id":2, "fullname":"mariah carey", "id":3, "fullname":"taylor swift"} Attendance {"id":1, "employee": 1,"activity_type": 1, timestamp: "2017-12-05 09:08", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day "id":2, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 10:13", "id":3, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 11:30", "id":4, "employee": 2,"activity_type": 2, timestamp: "2017-12-05 15:13", "id":5, "employee": 3,"activity_type": 2, timestamp: "2017-12-05 18:30", "id":6, "employee": 2,"activity_type": 1, timestamp: "2017-12-05 19:13", -interested in this for the activity type (1 for CHECKIN) and the date 2017-12-05, last of that employee id for that day "id":7, "employee": 3,"activity_type": 1, timestamp: "2017-12-05 20:30", -interested in this for the activity type (1 for … -
How can I upgrate plan on Heroku from Hobby-dev to Hobby Basic?
I would like to upgrate plan on Heroku with my Django app from Hobby-dev to Hobby Basic? At the moment heroku pg:info returns: Plan: Hobby-dev Status: Available Connections: 0/20 PG Version: 9.6.4 Created: 2017-11-12 19:20 UTC Data Size: 135.9 MB Tables: 19 Rows: 1272760/10000 (Above limits, access disruption imminent) Fork/Follow: Unsupported Rollback: Unsupported Continuous Protection: Off Add-on: postgresql-cub... I tried to use this but I am not sure which way should I choose. Any ideas how can I do this upgrade? -
How to move a file from a model's folder to another?
I have two models [1] TempFile(models.Model) and Company(models.Model) , when the view [2] save_records(request) is called I'd like to save & move the image from TempFile(models.Model) which is in folder /temporary_files/ to Company(models.Model) which is in folder /company_logo/. [1] models.py class Company(models.Model): logo = models.FileField(upload_to="company_logo") ... class TempFile(models.Model): unique_id = models.CharField(max_length=8) image = models.FileField(upload_to="temporary_files") ... [2] views.py def save_records(request): if request.method == 'POST': temp_file = TempFile.objects.get(unique_id=request.session['uuid']) Company.objects.create( logo = temp_file.image ... ) Here's the problem with this method, while the logo is saved the path of the folder stays /temporary_files/. I'd like to know how to save or move the image without quality loss and performance issue to Company(models.Model)'s company_logo folder ? -
Not able to send email from elastic beanstalk environment through my gmail email id
I'm using Django as the framework, Running inside docker and docker is running on AWS elastic beanstalk docker platform.So, I'm Trying to send email using my Gmail id it works fine in the local environment(in docker). BUt the same docker image running on elastic beanstalk docker fails to send emails and it is not even giving me an error or something.It is just not sending emails. If it is working fine in local environment why is that it not sending an email when running in the cloud? -
Why doesn't custom save method update another model while running Django test?
I have a custom save method on one model that updates the value of another model based on whether the current model is created or updated. I am trying to run a test to see if the value changes. Here is my code in the test. test.py yr.__setattr__('quantity_rcv', 200) yr.save() self.assertEqual(yr.quantity_rcv, lc_item.yarn_rcv) Over here lc_item.yarn_rcv should have changed to the yr.quantity_rcv value based on the custom save method which works fine when I test it with Django admin. Is the custom save method not working when I run test?