Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get django admin page working in Chrome?
I created superuser in Django and tried login into the admin page in Chrome. But it throws me this error Forbidden (403) CSRF verification failed. Request aborted. I tried to login into admin page using Microsoft Edge. It works in Microsoft Edge but it doesn't work in Chrome. This is my settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR,'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '5#k=p42no9i_cti@96zg1!=!9=4d645f-r%y+hvmi5r@sa#a!+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'basic_app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'learning_users.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'learning_users.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.Argon2PasswordHasher', 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.BCryptPasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', … -
Django model form saving simultaneously post request twice
I am using django-bootstrap-modal-forms 1.3.1 following https://pypi.org/project/django-bootstrap-modal-forms/ but if I run it's project of books it calls the post request to create book twice but saves the from once. As I am using it, it makes twice post request but both the request are saved one with empty file i.e one post saves all the fields of modal like title description, date but not the upload (file) and the next post saves all of it with upload simultaneously This is my model : class File(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) visible_to_home = models.ManyToManyField(Home, blank=True) # when none visible to all home visible_to_company = models.ManyToManyField(Company, blank=True) # when none visible to all company # To determine visibility, check if vtc is none or include company of user and if true, check same for home created_date = models.DateTimeField(auto_now=True) published = models.BooleanField(default=True) upload = models.FileField(blank=True, null=True, upload_to=update_filename) title = models.CharField(max_length=225, blank=True, null=True) description = models.TextField(blank=True, null=True) If I remove author then it works fine but as my requirement I need author. class FileForm(PopRequestMixin, CreateUpdateAjaxMixin, forms.ModelForm): class Meta: model = File fields = ('title', 'description', 'upload') View class FileCreateView(PassRequestMixin, SuccessMessageMixin, CreateView): template_name = 'file/upload-file.html' form_class = FileForm success_message = 'File … -
How to open authorization in the new window and override redirect_url in django-allauth?
I'm using django-allauth package. How can I open social oauth authorization flow in the new window and customize redirect_url? There is nothing in docs on this configuration. Maybe some of you guys did something similar in the past. I had a look at sources. I have a notion that there is some way through overriding Social Provider class. But what would be the configuration in this case? Thank you in advance. -
Saving multiple column values using a for loop in Django
In my database (SQLite), I would like to update every column in a given row by using a for loop through a dictionary. I've searched both SO and Django documentation, but have been unable to find any information regarding updating multiple columns via a for loop. I suspect that there's an easy solution to my problem, but I've run out of keywords to google. Here's a very simple example that boils the problem down to its core: models.py from django.db import models class author_ratings(models.Model): name = models.TextField() book_one = models.IntegerField() book_two = models.IntegerField() book_three = models.IntegerField() views.py from models import author_ratings ratings_dictionary = {'book_one': 10, 'book_two': 20, 'book_three': 30} current_author = author_ratings.objects.filter(name="Jim") for book,rating in ratings_dictionary: current_author.book = rating current_author.save() The problem: Instead of saving the values of 10, 20, and 30 into the corresponding columns of this author's row, Django throws the following error: "AttributeError: 'current_author' object has no attribute 'book'" The above information should be enough to fully understand the question, but I can provide any other details upon request. Thank you in advance for any assistance. -
How to deploy media files in django-heroku?
I am trying to deploy a django app on heroku. I'm currently using the package django-heroku as the standard setup. Under my models some media files that are uploaded using ImageField and I want them to be displayed in my templates. However, although they seem to point to the correct destination they are not being served. I've looked to similar questions here in SO and looked into the official package git repository looking for examples, however I did not find any example using the same configuration. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' . . . django_heroku.settings(locals()) template {% extends 'base_site.html' %} {% load i18n %} {% block content_title %}{% trans 'Manage Product Detail' %}{% endblock%} {% block content %} <div class="card"> <div class="carousel-inner" role="listbox"> {% for figure in product.figures.all %} <div class="item{% if forloop.first %} active{% endif %}"> <img src="{{ figure.image.url }}"> </div> {%endfor%} </div> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.description }}} </div> <div class="card-footer"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.description }}} </div> </div> {% endblock %} Although I can confirm that the media folder, subfolder and image exist (at the root of my project) … -
Celery tasks not being completely removed from queue
I have a celery task that calls itself (with do_stuff.apply_async(queue="foo")). Previously I have ran app.control.add_consumer("foo", reply=True) so my workers can consume from this queue. After some amount of time, I want to stop all the tasks from that queue and all running tasks that were launched from do_stuff. So I run this code: app.control.cancel_consumer("foo", reply=True) for queue in [i.active, i.scheduled, i.reserved]: for worker_name, worker_tasks in queue().items(): for task in worker_tasks: args = ast.literal_eval(task["args"]) if "do_stuff" in task["name"] and args[0] == crawler.name: app.control.revoke(task["id"], terminate=True) This "works" kind of. It does stop all the running tasks from do_stuff and it does clear the scheduled tasks (or at least I can't see any in Flower, after running this code). The problem is that if I run app.control.add_consumer("foo", reply=True) again, without running anything else, new tasks start running. That means that celery/redis, somehow, manage to keep some tasks somewhere. Why is that happening? Where are those "hidden" tasks saved? And how can I remove them? -
How to get mulitple values in view using form
i have a form in template with input field. i want to pass array like [2][3] in django view <input type="checkbox" class="form-check-input" name="accesses" value="myvalue" > <input type="checkbox" class="form-check-input" name="accesses" value="myvalue" > How can i pass those values and it in views like i am using getlist function where i am getting values but i want 2 values from single input field. accesses = request.GET.getlist('accesses') Some what similar to this <input type="checkbox" class="form-check-input" name="accesses" value1="2" value2="3"> and how can i get those values in views.py -
Is it possible to perform calculations on the data before returning the response?
I want to create an API, so that when an user requests certain type of data, I want to query database, and create an HTML based on that data and return it in side JSON. I'm pretty new to the django and the rest framework, but I already learned how to create basic API that serializes the model and returns it. Now I want to do something before returning the data. result will possibly look like this: { "html_response": "<table> (table based on the data) </table>" } -
queryset, union, order_by over an annotated field
It seems that Django is kind of an overthinker when it comes to order by a field. I need to make a union of two queries (queryset), the first one is ranked, the second one is not, in the final result I want a single queryset because it is going to be paginated. I'll give you an example using the User model so you can try this at home. from django.contrib.auth.models import User from django.db.models import F, Value, IntegerField from django.db.models.expressions import RawSQL queryset = User.objects a = queryset.filter(email__contains='a').annotate(rank=RawSQL("rank() OVER (ORDER BY id desc)", [], output_field=IntegerField())) b = queryset.filter(email__contains='b').annotate(rank=Value(None, output_field=IntegerField())) a.union(b).order_by(F('rank').desc(nulls_last=True)) # DatabaseError: ORDER BY term does not match any column in the result set. a.order_by(F('rank').desc(nulls_last=True)) # this is OK b.order_by(F('rank').desc(nulls_last=True)) # ProgrammingError: non-integer constant in ORDER BY # LINE 1: ...ERE "auth_user"."email"::text LIKE '%b%' ORDER BY NULL DESC ... Is this a Django bug? I'm using Django==1.11.17 -
Pandas not working in Django deployment on Heroku
I´m building an app with Django and hosting it in Heroku. Everything worked fine until I added Pandas recently. It seems to be some kind of problem with Pandas, codes associated with it simple don´t print on the HTML. The app works fine in my local development environment. Example I´m building a sort of product catalog. Where there is a product category header block and the products detail block. The problem is that when already published in Heroku the page does not show the products detail block, where I´m using Pandas. Here you have a screenshot of what I see in my development environment (sorry I use an image, but I found no other way to show the offline working page): Here you have the link to the published app (only shows the block headers): Link to published page Code Views def WorkflowContenidosView(request): productos = ProductosBase.pdobjects.all() productos = productos.to_dataframe() productos_fotos = ProductosBase.objects.order_by("producto") #productos = productos[productos.estatus_contenido == 1] general = productos.groupby(["categoria_producto", "producto"])[["producto"]].nunique() medidas = productos.groupby(["producto", "ancho", "largo"])[["largo"]].nunique() packaging = productos.groupby(["producto", "packaging"])[["packaging"]].nunique() categorias = Categorias_Producto.objects.all() marcas_base = Marcas.objects.all() colores_base = ColorBase.objects.all() colores = productos.groupby(["producto", "color"])[["color"]].nunique() fotos = productos.groupby(["producto", "foto_1", "foto_2"])[["producto"]].nunique() marcas_unique = productos.groupby(["producto", "marca"])[["marca"]].nunique() descripcion = productos.groupby(["producto", "descripcion"])[["descripcion"]].nunique() pedido_min = productos.groupby(["producto", "packaging", … -
Django ImageField is not updating when update() method is used
I am updating some of fields in model from views.py file. All other fields are updated properly when I use Profile.objects.filter(id=user_profile.id).update( bio=bio, city=city, date_of_birth=dob, profile_pic=profile_pic, gender=gender ) only, profile_pic = models.ImageField(blank=True) is not updated, Weird thing is when I check my Profile model from admins.py it shows me the file name which I uploaded, But my file is not shown in my /media directory(where I upload my all Images) views.py def edit_submit(request): if request.method == 'POST': profile_pic = request.POST.get('profile_pic') bio = request.POST.get('bio') city = request.POST.get('city') dob = request.POST.get('dob') gender = request.POST.get('gender') user_profile = Profile.objects.get(user=request.user) Profile.objects.filter(id=user_profile.id).update( bio=bio, city=city, date_of_birth=dob, profile_pic=profile_pic, gender=gender ) return HttpResponseRedirect(reverse('profile', args=[user_profile.id])) I think only text is stored in ImageField and Image is not uploded to /media directory Note: I am using <input type="file" name="profile_pic" class="change_user_img"> for getting image from template -
ImportError django is not found
i install the django framework in virtual env. now it is given me the importerror. (WebEnvironment) D:\conda project\web\mysite>python manage.py runserver Traceback (most recent call last): File "manage.py", line 8, in from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available o n your PYTHONPATH environment variable? Did you forget to activate a virtual env ironment? strong text -
Warning while trying to update the db through django object in the views.py
I have an html template that has list of students. Every student has a checkbox near his name in a form. When i submit the form it updates the DB with the status of checkbox. When i try to update related db object i get below error: Exception Type: ValueError invalid literal for int() with base 10: 'False' The error generating line is : StudentClassLessonAttendance.objects.filter(student_id=stu, semester_id=last_semester, dateadded=coursedate, lessonhour=lessonhour, cls_id=stuclass, course_id=stucourse).update(yoklama=True) My view is : def update_daily_attendance_all(request, stuclass=None, stucourse=None, courseteacher_uuid=None, lessonhour=None): if request.method == 'POST': last_semester = Semester.objects.all().order_by("-year").first() staff = get_object_or_404(Staff, user=request.user) today = nicosia_date(datetime.today()).date() classyear = request.POST.getlist('classyear')[0] classname = request.POST.getlist('classname')[0] coursename = request.POST.getlist('coursename')[0] coursedate = request.POST.getlist('coursedate')[0] checkedstudentslist = [] for studentid in request.POST.getlist('studentid'): checkedstudentslist.append(studentid) allstudentslist = [] allstudents = StudentClassLessonAttendance.objects.filter(semester_id=last_semester, dateadded=coursedate, lessonhour=lessonhour, cls_id=stuclass, course_id=stucourse).values('uuid', 'student__name', 'student__surname', 'student_id', 'yoklama').order_by("student__name") for student in allstudents: allstudentslist.append(str(student['student_id'])) uncheckedstudentslist = list(set(allstudentslist) - set(checkedstudentslist)) for stu in checkedstudentslist: StudentClassLessonAttendance.objects.filter(student_id=stu, semester_id=last_semester, dateadded=coursedate, lessonhour=lessonhour, cls_id=stuclass, course_id=stucourse).update(yoklama=True) for stu in uncheckedstudentslist: StudentClassLessonAttendance.objects.filter(student_id=stu, semester_id=last_semester, dateadded=coursedate, lessonhour=lessonhour, cls_id=stuclass, course_id=stucourse).update(yoklama=False) attendancelist = StudentClassLessonAttendance.objects.filter(semester_id=last_semester, dateadded=coursedate, lessonhour=lessonhour, cls_id=stuclass, course_id=stucourse).values('uuid', 'student__name', 'student__surname', 'student_id', 'yoklama').order_by("student__name") return redirect(reverse('list-attendance-courses-all')) -
NoReverseMatch at /rubies/users/1/: Reverse for 'story' with arguments '(1, '')' not found
NoReverseMatch at /rubies/users/1/ Reverse for 'story' with arguments '(1, '')' not found. 1 pattern(s) tried: ['rubies/users/(?P[0-9]+)/stories/(?P[0-9]+)/$'] I faced the same problem with my story page, where the error Reverse for 'user' with arguments '(1, '')' not found came up. Gladly, somebody helped me solve that problem. However, I cannot manage to find the solution to this one, even though it's practically the same. user.html {% extends "rubies/base.html" %} {% block content %} <ul class="list-group"> <li class="list-group-item"> Name: {{ user.username }} </li> <li class="list-group-item"> <ul> Stories: {% if story_id %} {% for story in user.story.all %} <li> <a href="{% url 'rubies:story' user.id story.id %}">{{ story.title }}</a> </li> {% endfor %} {% else %} {% if current_user == story.author.id %} <h2 class="bg-warning">You have not written any stories yet.</h2> <a href="{% url 'rubies:story' user.id story.id %}"> <span class="fas fa-plus-circle" aria-hidden="true"></span> </a> {% else %} <h2 class="bg-warning"> {{ story.author.username }} has not written any stories yet. </h2> {% endif %} {% endif %} </ul> </li> </ul> {% endblock %} user.view def user_view(request, user_id): if user_id is not None: user = get_object_or_404(User, pk=user_id) else: user = User() context = { 'user_id': user_id, 'name': user.name, 'surname': user.surname, 'username': user.username, 'password': user.password, 'email': user.email } return render(request, … -
django - change list in POST request
I have a tuple list and wanted to delete or add tuples in it depending on what button has been pressed. Adding tubles is functioning fine but my problem is, that for some reason if Im clicking on the button to delete a tuple, the list resets back the time to the state before the delete happened. For example I have a list: ctestformat = [('sung', 4, 15), ('ren', 3, 27), ('lexe', 4, 39)] after deleting the number 15 I get: ctestformat = [('ren', 3, 27), ('lexe', 4, 39)] But after getting another POST request to delete or add, the list resets to the first state as if nothing got deleted Here is my view to add and delete tuple depending on which button was clicked: def editorstart(request, ctestformat=[]): if request.method == 'POST': """If clicked on create gap button, create a new gap and put it in ctestformat""" if 'create_gap' in request.POST: selectedgap = request.POST['sendgap'] startindex = int(request.POST['startpoint'])-13 ctestformat.append((selectedgap, len(selectedgap), startindex)) ctestformat.sort(key=operator.itemgetter(2)) """if clicked on deletegap, delete the gap from ctestformat""" elif 'deletegap' in request.POST: deleteindex = request.POST['deletegap'] test = [t for t in ctestformat if t[2] != int(deleteindex)] ctestformat = test If you have any other questions, just ask … -
ArrayModelField vs ListField with EmbeddedModelField
What is the difference between ArrayModelField and ListField with EmbeddedModelField inside? For me it looks like both could be used for the same purposes and would be stored the same way in database. field = ListField(EmbeddedModelField(model_container=Model)) vs field = ArrayModelField(model_container=Model) -
How to handle both save and save-as button with django class-based view
What I want to do is just a simple update view with two submit button: namely save which simply saves the update; and also save-as button, which of course save a copy of the updated form to the database and leave the original data unedited. Now I know how to do this in function based view, provided that my page_edit.html has two button: <input type="submit" class="btn btn-danger" name = "save" value="Save changes"> <input type="submit" class="btn btn-success" name = "save_as" value="Save as new Page"> Then my simplified view would be something along: def page_edit(request, pk): if request.method == 'POST': if 'save' in request.POST: instance = Page.objects.get(pk=pk) elif 'save_as' in request.POST: instance = Page.objects.create() p = PageForm(request.POST, request.FILES, instance=instance) if p.is_valid(): """write to db""" p.clean() p.save() context = {'form': p, 'p_data_in': p.cleaned_data, 'p': p.instance} return render(request, '/template/page_detail.html', context) else: instance = Page.objects.get(pk=pk) p = PageForm(instance=instance) context = {'form': p, 'p': p.instance} return render(request, '/template/page_edit.html', context) However, I'm a bit puzzled navigating with class-based view. I tried using UpdateView in this way: class PageEdit(UpdateView): model = Page form_class = PageForm template_name = '/template/page_edit.html' def form_valid(self, form): if 'save_as' in self.request.POST: # current = self.get_context_data() f = self.form_class(self.request.POST, self.request.FILES) f.save() return super(PageEdit, self).form_valid(form) It … -
ChannelsLiveServerTestCase failing with error while following Django Channels tutorial (part 4)
I am trying to follow the 4 part channels tutorial, however I am getting an error on the last part where we run selenium to test against a live server. It's not the end of the world as I can still run the server with no problems, however it limits my ability to test which is a shame. I have the full details in the closed issue below (to avoid repetition) https://github.com/django/channels/issues/1207 I have somehow also managed to get these tests to run and pass with channels version 2.0.2 since opening the issue, however versions 2.1.6 still fails. I'm unfortunately not experienced enough with the packages in the error trace to diagnose the problem myself. Thanks in advance, hopefully this is enough information. I can provide more on request. -
Django date-range-picker. What is we should give in place of event days "'start_date':DatePickerInput().start_of('event days')"
I am trying to use DatePickerInput. I am not able to understand what should be given in place of event days in below code. # File: forms.py from bootstrap_datepicker_plus import DatePickerInput, TimePickerInput from .models import Event from django import forms class EventForm(forms.ModelForm): class Meta: model = Event fields = ['name', 'start_date', 'end_date', 'start_time', 'end_time'] widgets = { 'start_date':DatePickerInput().start_of('event days'), 'end_date':DatePickerInput().end_of('event days'), 'start_time':TimePickerInput().start_of('party time'), 'end_time':TimePickerInput().end_of('party time'), } This is the tutorial I am following: https://media.readthedocs.org/pdf/django-bootstrap-datepicker-plus/latest/django-bootstrap-datepicker-plus.pdf -
How to get Mulitple Data from Template to View
I have a form with input field like this. How can i get those values in django. i am using values="[1][{{ functionality.id }}]" for multiple loops. template.html <form action="" method="POST"> <tr> {% for functionality in functionalities %} <td>{% ifchanged %}{{ functionality.acl_controller}}{% endifchanged %}</td> <td> {{ functionality.acl_functionality }} </td> <td> <div class="form-check form-check-flat text-dark"> <label class="form-check-label"> <input type="checkbox" class="form-check-input" values="[1][{{ functionality.id }}]"> . <i class="input-helper"></i></label> </div> </td> <td> <div class="form-check form-check-flat text-dark"> <label class="form-check-label"> <input type="checkbox" class="form-check-input" values="[2][{{ functionality.id }}]"> . <i class="input-helper"></i></label> </div> </td> </tr> {% endfor %} </form> Views.py @login_required def AclView(request): form = ACLForm() functionalities = AclFunctionality.objects.all().order_by('acl_controller') companies = Company.objects.exclude(company_is_deleted=True) query = request.GET.get('query') company = 0 if query: # list_query = companies company = Company.objects.get(id=query) print(company) return render(request, 'acl/acl-dashboard.html', { 'functionalities': functionalities, 'companies': companies, 'company': company, 'form': form }) I want to save the multiple data in AclRoleAccess Model(Database) Models.py class AclRoleAccess(models.Model): acl_role = models.ForeignKey(ACLRoles, on_delete=models.CASCADE) acl_company = models.ForeignKey(Company, on_delete=models.CASCADE) acl_functionality = models.ForeignKey(AclFunctionality, on_delete=models.CASCADE) acl_has_access = models.BooleanField() class Meta: db_table = "acl_role_accesses" How i can save that 2d array in AclRoleAccess multiple data at same time where acl_company=1 and acl_roles=1 or 2 (first array values) -
Django login_required for mod_wsgi access control
I want to restrict access to certain media files to logged in users in django with mod_wsgi. I can't find any way to do so. I managed to restrict the access following the instructions here: https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/apache-auth/ However, if I do it this way, I have to enter the credentials and password again whenever I want to access the files in a htaccess popup style. I can't find out how to tell apache/mod_wsgi that the already authorized user has access to that certain folder and therefore can see the media files, without having to enter his credentials again. I am currently using the same apache to serve the media files that also hosts the website, I am planning to move the media folder to another cloud server though in the future. Following the tutorial I use the following settings in my apache.conf: <Location "/media/secret_folder"> AuthType Basic AuthName "Access needed to access this media file" Require valid-user AuthBasicProvider wsgi WSGIAuthUserScript /path/to/mysite.com/mysite/wsgi.py </Location> I use from django.contrib.auth.handlers.modwsgi import check_password as check_password function in my wsgi.py. As I don't know where to start looking for the solution, my guesses are either creating my own check_password function or using another AuthType in the Location attribute. … -
configure JWT session Timeout in django
i have configured JWT in django with session timeout for 15 minutes. But i don't want to expire session when user was not ideal.i want to expire the session when the user is ideal.Is that possible through JWT configuration. -
Django Custom Calendar based on two models
General Concept: Requirement for a view that would display current week with events (event time in brackets) in each day column: Mon Tue Wed Thu Fri (10:00) (10:30) (11:30) (11:30) (12:00) (13:00) (13:00) Conflicting event times should be somehow marked and ideally each time frame should be in row and not aligned to top as in the currently working solution. Currently working solution (screenshot and code), table header has Month and Day of Month (day of week), all events are in one row in date matching columns: views.py: def get_week(curr_date): week_start = curr_date - timedelta(days=curr_date.weekday()) week_end = week_start + timedelta(days=7) delta = week_end - week_start week = list() for i in range(delta.days): week.append(week_start + timedelta(i)) return week def calendar(request): week_start = date.today() - timedelta(days=date.today().weekday()) patients = Patient.objects.filter(owner=request.user) sessions = Session.objects.filter(patient_id__in=patients, sessionDate__gte=week_start).order_by('sessionDate') return render(request, 'psychotherapist/calendar.html', {'week': get_week(date.today()), 'sessions': sessions}) calendar.html: <table class="table table-dark table-hover"> <thead> <tr class="d-flex"> {% for w in week %} <td class="col">{{ w|date:'M d (D)' }}</td> {% endfor %} </tr> </thead> <tbody> <tr class="d-flex"> {% for w in week %} <td class="col"> {% for s in sessions %} {% if s.sessionDate|date == w|date %} <button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#edit_{{ s.pk }}" name="{{ s.pk }}" title="Edytuj sesję"> … -
TemplateDoesNotExist at /project/login/ registration/login.html
when I try to go to my login page, I always get this: TemplateDoesNotExist at /rubies/login/ registration/login.html My login file is in the folder templates, just like all the other html files. I tried creating a register folder and putting it in, but it still didn't work! Here is (part of) my settings.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'project.apps.ProjectConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ROOT_URLCONF = 'project.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'project.wsgi.application' And my urls.py : from django.urls import path from rubies import views from django.contrib.auth import views as auth_views app_name = 'rubies' urlpatterns = [ path('', views.index_view, name='index'), path('register/', views.register_view, name='register'), path('login/', auth_views.LoginView.as_view(), name='login'), path('users/<int:user_id>/', views.user_view, name='user'), path('users/<int:user_id>/stories/<int:story_id>/', views.story_view, name='story'), ] Does anyone know what I am doing wrong? Thank you! -
i cant make migrations for an app in django 2.1.4
Please help out I am designing a blog app using django 2.1.4, actually following the instructions from a book "Django by example" by antonio mele which uses django 1.8. However after creating the app and adding the blog model, i tried applying the migration for the new model and i get this error message. Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_c ommand_line utility.execute() File "C:\Users\public\django\my_env\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\public\django\my_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\public\django\my_env\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\public\django\my_env\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\public\django\my_env\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 724, in exec_module File "<frozen importlib._bootstrap_external>", line 860, in get_code File "<frozen importlib._bootstrap_external>", line 791, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\public\django\mysite\blog\models.py", line 5 STATUS_CHOICES = (