Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
CSS not working while in deployment in django
This is my file structure Project asgi.py . . . main admin.py . . static css files templates users admin.py . . static files static (created after collectstatic) db.sqlite3 manage.py Static url and root STATIC_URL = "/STATIC/" STATIC_ROOT = OS.PATH.JOIN(BASE_DIR, 'static') I did collectstatic and it works properly all files are coped to /static/ folder now this all works fine with running with debug = true but when I set debug false none of the css loads. example of a css in html <link rel="stylesheet" href="{% static 'main/style.css' %}"> this is happening only with any templates inside "main" app, for "users" app all the css is loading properly -
Django Apache 2.4.18 Ubuntu 403
I am trying to configure my django app with Apache 2.4.18.. I am using Django 3.0.5 and Python 3.8.2., on Ubunu 16.04. Everything works fine in runserver mode. Forbidden You don't have permission to access this resource. This is my apache config gile Listen 80 <VirtualHost *:80> ServerAdmin xxx@xxx.com ServerName servername.net DocumentRoot /srv Alias /static /srv/tacdb/mysite/static <Directory "srv/tacdb/mysite/static"> Require all granted </Directory> Alias /media /srv/tacdb/mysite/media <Directory "srv/tacdb/mysite/media"> Require all granted </Directory> ErrorLog ${APACHE_LOG_DIR}/portal_error.log CustomLog ${APACHE_LOG_DIR}/portal_access.log combined WSGIDaemonProcess mysite python-home=/srv/tacdb/virtualenvironment/project_1 python-path=/srv/tacdb WSGIProcessGroup mysite WSGIScriptAlias / /srv/tacdb/mysite/wsgi.py <Directory /srv/tacdb/mysite> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> configtest is ok and server status is ok. root@test-tools:~/srv# systemctl status apache2.service ● apache2.service - LSB: Apache2 web server Loaded: loaded (/etc/init.d/apache2; bad; vendor preset: enabled) Drop-In: /lib/systemd/system/apache2.service.d └─apache2-systemd.conf Active: active (running) since Thu 2020-04-02 15:18:20 UTC; 5min ago Docs: man:systemd-sysv-generator(8) Process: 26327 ExecStop=/etc/init.d/apache2 stop (code=exited, status=0/SUCCESS) Process: 25036 ExecReload=/etc/init.d/apache2 reload (code=exited, status=0/SUCCESS) Process: 26356 ExecStart=/etc/init.d/apache2 start (code=exited, status=0/SUCCESS) CGroup: /system.slice/apache2.service ├─26372 /usr/sbin/apache2 -k start ├─26375 /usr/sbin/apache2 -k start ├─26376 /usr/sbin/apache2 -k start └─26377 /usr/sbin/apache2 -k start Apr 02 15:18:19 test-tools systemd[1]: Stopped LSB: Apache2 web server. Apr 02 15:18:19 test-tools systemd[1]: Starting LSB: Apache2 web server... Apr 02 15:18:19 test-tools apache2[26356]: * Starting Apache … -
SQL Lite to PostgreSQL migration ERROR Django 3.0
Situation I am guessing that the problem relates to that I may have incorrectly altered my SQL lite database to PostgreSQL. After the migration I have cutted out my Login fully and created and used a simple register and login. But than I brought back the whole app where I have written the sql lite. Previously I did not asked for the user to give email address as well and now in the new version I do. Registration and login works because if I log in that is when I get the error message otherwise works. Homepage also works perfectly even if I am logged in. ERRORS localenvironmenthome/accounts Confirm Form ResubmissionThis webpage requires data that you entered earlier in order to be properly displayed. You can send this data again, but by doing so you will repeat any action this page previously performed. Press the reload button to resubmit the data needed to load the page. ERR_CACHE_MISS Than after the reload localenvironmenthome/accounts gave the following error message ValueError at /accounts/ The view accounts.decorators.wrapper_function didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://localhost/accounts/ Django Version: 3.0 Exception Type: ValueError Exception Value: The view accounts.decorators.wrapper_function didn't … -
SessionId cookie not set on Chrome (Django App)
I am having problems accessing some third-party cookies on Chrome. Chrome version is 80.0.3987.100 (Official Build) (64-bit) and I suppose this already have the new implementation of SameSite cookies set to Lax. However, in the Django settings I have added the following: SESSION_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = None CSRF_COOKIE_SAMESITE = None with no luck. You can see there are no Cookies in the Request header above I have tried the request I am having troubles executing from Chrome on Postman. I get exactly the same result until I pass Cookie: sessionid: <some_id>. It probably is worth mentioning that this whole things works with no problems on Firefox (where I can see the Cookie set properly in the request Headers). If anyone has any ideas it would be greatly appreciated. -
Publish Django project with gunicorn and NGINX
Im trying to publish my Django project with NGINX and gunicorn, but I get permission denied from gunicorn. My last steps what I did. mkdir /home/sama/websites cd /home/sama/websites mkdir test_project cd test_project create Virtualenvirement for this project virtualenv --python=/usr/bin/python3.8 venv Virtualenvirement activate source venv/bin/activate Gunicorn & Django install pip3 install gunicorn pip3 install django create project cd .. django-admin startproject config test_project allow firewall to port 8000 sudo ufw allow 8000 run first test python manage.py runserver 0.0.0.0:8000 open my server ip on webbrowser myIP:8000 I can see Django basic page stop server CTRL + C testGunicorn gunicorn --bind 0.0.0.0:8000 config.wsgi testagain on webbrowser Again I can see Djangos page Server stop CTRL + C exit virtualenvirement deactivate config Gunicorn create 2 files in /etc/systemd/system/ gunicorn.socket and gunicorn.service edit this files sudo nano /etc/systemd/system/gunicorn_test_project.socket /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn daemon [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sama Group=www-data WorkingDirectory=/home/sama/websites/test_project ExecStart=/home/sama/websites/test_project/venv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock config.wsgi:application [Install] WantedBy=multi-user.target test socket sudo systemctl start gunicorn.socket sudo systemctl enable gunicorn.socket systemlink created, check it file /run/gunicorn.sock Output: /run/gunicorn.sock: socket curl --unix-socket /run/gunicorn.sock localhost And now I get permission denied I already set permission for the folder test_project to … -
How to retrieve data from a form in Django
I am working on a weather app where the client will be entering the name of the city in a search bar, and the name will be used to gain weather data from an API. To get the name of the city from the form, I have created this condition in view: if request.method == 'POST': city = request.data print(city) however when being printed, this error occurs: 'WSGIRequest' object has no attribute 'data' What am I doing wrong? Or is there a completely different way to do this? Edit: I have added the code suggested, by using the name. Now i get the data obtained as 'None' Here is the form: <form method="POST" name="data">{% csrf_token %} <div class="field has-addons"> <div class="control is-expanded"> <input class="input" type="text" placeholder="City Name"> </div> <div class="control"> <button class="button is-info" type="submit"> Search City </button> </div> </div> </form> -
how to disable password after inheriting AbstractUser to make a custom user
I followed what django docs said about inheriting AbstractUser to make a custom user for easy future changes https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project Anyway, I have it now on the admin menu as a different page, it now looks like this I basically want to disable that input (and others as well). How do I do that? -
django filter by datetime range using a datetimepicker
i am doing an eCommerce project and this is my analytics view : def analytics(request): orders = None total = 0 predicate = request.POST # or request.data for POST if predicate.get('from_date', None) is not None : orders = Order.objects.filter(timestamp__gte=predicate['from_date']) total = orders.aggregate(total_price=Sum('total')) context= { 'orders': orders, 'total' : total } return render(request,'analytics.html', context) it's pretty simple : i am letting the user chose a date with jquery datetimepicker and iam filtering the Order model based on that date to get all order starting that chosen date (period) it works fine but what i really want to do is let's say the user chose a 5 days period , i want to get is a list of orders in each day during that 5 day period : something like this : day 1: 3 orders day 2: 2 orders day 3: 5 orders day 4: 1 orders day 5: 8 orders and calculate total orders price for each day so i can graph that data using Chart.js -
CSS doesn't load properly with django
For a project, i try to make a website with django. I think I've set everything up right but when I go to my website, the css sheet doesn't load. When I go to my website, I have this. Here's my folders Installed apps : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig' Main urls.py : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')) ] Home urls.py : from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] CSS File : html{ background-color: red; } HTLM File : {% load static %} <!DOCTYPE html> <html> <head> <title>Chasse au trésor du lycée Renoir</title> <link rel="stylesheet" type="text/css" href="{% static 'css/index.css' %}"> </head> <body> <h1>Hello World</h1> </body> </html> -
How to display post in two columns in one row using bootstrap 4.0 with the backend django
Two get the two columns in single row using Bootstrap 4.0, We can achieve this using the following code. <div class="container"> <div class="row"> <div class="col">Column</div> <div class="col">Column</div> <div class="w-100"></div> <div class="col">Column</div> <div class="col">Column</div> </div> </div> How do I apply the same in the following code when the data is iterating using for loop? Here is my html file. <div class="container"> <div class="row"> <div class="col-md-8 mt-3 left"> {% for post in medicine_list %} <div class="col"> <div class="card mb-4"> <div class="card-body"> <h6 class="card-title"><a href="{% url 'medicine_detail' post.slug %}"> {{ post.title }}</a></h6> </div> </div> </div> {% endfor %} </div> {% block sidebar %} {% include 'sidebar.html' %} {% endblock sidebar %} </div> </div> I'm getting confuse because of the for loop and the <div class="w-100"></div> tag. Any help would be really appreciable. Thanks. -
django-haystack with solr index multiple models but only one indexed
I had two SearchIndexes with exactly same fields such as: class TopicIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True, template_name="topic_template.txt") id = indexes.IntegerField(model_attr='id') title = indexes.CharField(model_attr='title') extra_info = indexes.CharField() type = indexes.CharField(default="topic") def get_model(self): return Topic def index_queryset(self, using="default"): return self.get_model().objects.all() def prepare_extra_info(self, obj): return "/media/" + str(obj.cover) class ReviewIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True, template_name="review_template.txt") id = indexes.IntegerField(model_attr='id') title = indexes.CharField() extra_info = indexes.CharField() type = indexes.CharField(default="review") def get_model(self): return Review def index_queryset(self, using="default"): return self.get_model().objects.all() def prepare_title(self, obj): return obj.topic.title def prepare_extra_info(self, obj): return obj.reviewer.name One is related to the other one. And I am trying to index them two into one solr core with schema like: <fields> <field name="id" type="string" indexed="true" stored="true" multiValued="false" required="true"/> <field name="django_ct" type="string" indexed="true" stored="true" multiValued="false"/> <field name="django_id" type="string" indexed="true" stored="true" multiValued="false"/> <field name="text" type="edge_ngram" indexed="true" stored="true" multiValued="false" /> <field name="title" type="text_en" indexed="true" stored="true" multiValued="false" /> <field name="extra_info" type="text_en" indexed="true" stored="true" multiValued="false" /> <field name="type" type="text_en" indexed="true" stored="true" multiValued="false" /> <uniqueKey>id</uniqueKey> </fields> However, every time I did either rebuild_index or update_index, it indexes both models: Removing all documents from your index because you said so. All documents removed. Indexing 9 topics Indexing 19 reviews Solr only has second model indexes in its documents as I … -
Add confirm password field in modelform in django only with one password field
I want to add the confirm password field in django modelform and validate both password and confirm password. After entering the details through template that data will be stored in database. But only three fields will be added to database such as firstname,lastname and email. so, i want to add the all fields data into database. Here is my model: class Register(models.Model): first_name = models.CharField(max_length=30, blank=False) last_name = models.CharField(max_length=30, blank=False) email = models.EmailField(max_length=50, blank=False) password = models.CharField(max_length=12, blank=False) Here is my modelform : class SignUpForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) password_confirm = forms.CharField(widget=forms.PasswordInput()) class Meta: model = Register fields = ['first_name', 'last_name', 'email','password'] def clean(self): cleaned_data = super(SignUpForm, self).clean() password = cleaned_data.get("password") confirm_password = cleaned_data.get("password_confirm") if password != confirm_password: raise forms.ValidationError( "password and confirm_password does not match" ) Here is my view.py file : def auth_register(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): form.save() return HttpResponse('data has been saved...!!') else: form = SignUpForm() return render(request, 'auth-register.html', {'form': form}) Here is template code: <form method="post" action="">{%csrf_token%} <div class="row"> <div class="form-group col-6"> <label for="first_name">First Name : </label> <input id="first_name" type="text" class="form-control" name="first_name" autofocus=""> </div> <div class="form-group col-6"> <label for="last_name">Last Name : </label> <input id="last_name" type="text" class="form-control" name="last_name"> </div> </div> <div class="form-group "> … -
How to perform calculations in abstract models in Django
I'm using an abstract base class to perform simple calculations in my models as below: class Base(models.Model): name = models.CharField(max_length=100, null=True) width = models.DecimalField(max_digits=10, decimal_places=2, default=1, validators=[MinValueValidator(1)]) length = models.DecimalField(max_digits=10, decimal_places=2, default=1, validators=[MinValueValidator(1)]) # I'm sure that this part is not correct, I have copied it # from a regular model thinking that this would work, but it didn't def save(self, *args, **kwargs): self.building_area = self.room_area + self.hall_area super().save(*args, **kwargs) class Meta: abstract = True class Room(Base): room_area = models.DecimalField(max_digits=10, decimal_places=2, default=1, validators=[MinValueValidator(1)]) def save(self, *args, **kwargs): self.room_area = self.length*self.width super().save(*args, **kwargs) def __str__(self): return self.name class Hall(Base): hall_area = models.DecimalField(max_digits=10, decimal_places=2, default=1, validators=[MinValueValidator(1)]) def save(self, *args, **kwargs): self.hall_area = self.length*self.width super().save(*args, **kwargs) def __str__(self): return self.name Can someone suggest how to implement such kind of calculations? -
How to import request.user into TemplateVew in djnago
I need to know how I can check if a user is authenticated user the TemplateView methods of rendering pages. i have added this into my context processors: TEMPLATE_CONTEXT_PROCESSORS = [ 'django.contrib.auth.context_processors.auth', ] my views.py currently looks like : from django.shortcuts import render from CreateVuln.forms import * from django.views.generic import TemplateView from django.template import RequestContext from pages.decorators import * vulnform = vulnform class Dashboard(TemplateView): template_name = 'vuln_pages/Create_Vuln.html' def get(self, request): Outform = { 'vulnform': vulnform, } return render(request, self.template_name, Outform) def post(self, request): forminput = vulnform(request.POST or None) if forminput.is_valid(): forminput.save() forminput = vulnform() inoutform = { 'vulnform': forminput, } return render(request, self.template_name, inoutform, ) else: inoutform = { 'vulnform': vulnform, } return render(request, self.template_name,inoutform ) # Create your views here. class ViewVulns(TemplateView): template_name = 'vuln_pages/Create_Vuln.html' def get(self, request): return render(request, self.template_name) I want to make it so the page cannot be viewed with either a GET request and cannot be updated with a POST request. i've tried using RequestContext. but the documentation seems convoluted and i cannot seem to understand how to use it. -
django: app not found when trying to import in urls
I am using Django 3. I have the following project structure: I am trying to import from my app "users" the "views" file as "users_view" in the main "urls.py" in django_devel_app from users import views as users_views the app is added in my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', #Core authentication framework and its default models. 'django.contrib.contenttypes', #Django content type system (allows permissions to be associated with models). 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'projects.apps.ProjectsConfig', 'users.apps.UsersConfig', Nevertheless I am not able to do that in pycharm. It does not find the app "users and underlines "users" in urls.py saying "unresolved reference"? -
how to create a nested API (CRUD) using Django?
i have a problem and i got very tired. i have a Service Model and it has a lot of relation with other models! This is my model: class Service(models.Model): user_iduser = models.ForeignKey(User, models.DO_NOTHING, db_column='User_idUser') # Field name made lowercase. request_date = models.DateTimeField(blank=True, null=True) country = CountryField(blank_label='(إختر الدولة)') # ++++++++++++++++++ insurance = models.OneToOneField(Insurance, models.DO_NOTHING, blank=True, null=True) omra = models.OneToOneField(Omra, models.DO_NOTHING, blank=True, null=True) organized_journey = models.OneToOneField(OrganizedJourney, models.DO_NOTHING) other = models.OneToOneField(Other, models.DO_NOTHING, blank=True, null=True) temp_hotel_reservation = models.OneToOneField('TempHotelReservation', models.DO_NOTHING, blank=True, null=True) temp_ticket = models.BooleanField(blank=True, null=True) ticket = models.OneToOneField('Ticket', models.DO_NOTHING, blank=True, null=True) travel_hotel_reservation = models.OneToOneField('TravelHotelReservation', models.DO_NOTHING, blank=True, null=True) visa = models.OneToOneField('Visa', models.DO_NOTHING, blank=True, null=True) visa_rdv = models.BooleanField(blank=True, null=True) visa_request_form = models.BooleanField(blank=True, null=True) client = models.ManyToManyField("Client") is_active = models.BooleanField(default=True) class Meta: managed = True db_table = 'service' unique_together = (('id', 'user_iduser'),) def __str__(self): return f'service to client {self.country}' the problem is: i want to create an API for this model and it will contains a nested APIs of other model like this: { clients: [ { firstName_ar, lastName_ar, firstName_fr, lastName_fr, passport_id, phone, email_fb, date_birth place_birth }, { firstName_ar, lastName_ar, firstName_fr, lastName_fr, passport_id, phone, email_fb, date_birth place_birth } ] country: 'DZ', insurance: { number: 1245454, } || False, omra:{ food: true, duration: 15, start_date: '2020-04-05', hotel_name: … -
Django ValueError: Field 'id' expected a number but got ' '
I keep having a problem with Django. In my website I've got a simple form for adding new items to the database. I'd like the items and the user who added them to be related just as with a post and its author. The first one (AddInfo) let the user add, through a form, the items. Signup let the user authenticate first. class AddInfo(CreateView): model = Info fields = '__all__' success_url = reverse_lazy('home') def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'search/signup.html', {'form': form}) In my models.py I've got this, where 'utente' (the last field), should be the user who added the item. But when I try to migrate I've got this error: ValueError: Field 'id' expected a number but got ' '. class Info(models.Model): band = models.CharField(max_length=200) disco = models.CharField(max_length=200) etichetta_p = models.CharField(max_length=200) etichetta_d = models.CharField(max_length=200) matrice = models.CharField(max_length=200) anno = models.PositiveIntegerField(default=0) cover = models.ImageField(upload_to='images/') utente = models.ForeignKey(User, on_delete=models.CASCADE) -
uwsgi --http-timeout and django
I have an issue with uwsgi handling requests for django application. uwsgi is started with the follwing parameters: uwsgi --http :8000 --wsgi-file djangoapp/wsgi.py --http-timeout 10 There 2 issues that I have. 1) There is not error message generated by uwsgi when the timeout is reached and connection is cut 2) Django processing continues I reviewed all configuration options and didn't find a way to configure the desired behaviour. Any suggestions? -
Why does the field validation (fields level and object level both) in the serializer not work?
I need to implement a limitation for creating an instance of the model so that if the Vendor model has the status active=True, then a validation error will appear. models.py class Vendor(models.Model): active = models.BooleanField(default=False) ... class VendorContacts(models.Model): vendor = models.ForeignKey('Vendors', related_name='contacts', on_delete=models.CASCADE) email = models.CharField(max_length=80, blank=True, null=True) ..... serializer.py class VendorContactCreateSerializer(serializers.ModelSerializer): email = serializers.CharField(validators=[RegexValidator(regex=r'[^@]+@[^\.]+\..+', message='Enter valid email address')]) vendor = serializers.PrimaryKeyRelatedField(queryset=Vendors.objects.all(), required=False, allow_null=True) class Meta: model = VendorContacts fields = ('vendor', 'contact_name', 'phone', 'email', 'primary', ) def create(self, validated_data): phone = validated_data.pop('phone', None) vendor = validated_data.pop('vendor', None) result = re.sub('[^0-9]', '', phone) contact = VendorContacts.objects.create(vendor=vendor, phone=result, **validated_data) return contact def validate_email(self, value): print('Start validation') exist_contact = VendorContacts.objects.filter(email=value) if exist_contact: vc = get_object_or_404(VendorContacts, email=value) v = vc.vendor if v.active: raise serializers.ValidationError('Email {} already exists'.format(value)) return value But validation doesn't work. Also the variant with validation at the object level def validation() does not work: -
How to handle files in Django Rest Framework?
I'm building an Angular + Django project, and I need to add some files to it, the idea is this model Ticket should receive some files, like imgs or pdf ... Wich Field should I use in the model? FileField? class Ticket (models.Model): titulo = models.CharField(max_length=100, blank=True) estagio = models.ForeignKey( Estagio, related_name='tickets', on_delete=models.CASCADE, null=True) cliente = models.ForeignKey(Cliente, on_delete=models.CASCADE, null=True) org = models.ForeignKey(Organizacao, on_delete=models.CASCADE, null=True) produto = models.ManyToManyField(Produto) valorestimado = models.IntegerField(null=True) termometro = models.CharField(max_length=100, null=True, blank=True) vendedor = models.ForeignKey( Vendedor, on_delete=models.CASCADE, null=True) vendedorext = models.ManyToManyField( VendedorExt, related_name='leads', blank=True) obs = models.ManyToManyField(Obs, related_name='tickets') status = models.CharField(max_length=155, blank=True, default='Aberto') mtvperd = models.CharField(max_length=155, null=True, blank=True) cmtperd = models.CharField(max_length=155, null=True, blank=True) created = models.ForeignKey(Created, on_delete=models.CASCADE, null=True) updated = models.ManyToManyField(Updated) def __str__(self): return str(self.titulo) And How can I handle this img in the view? : class TicketViewSet(viewsets.ModelViewSet): queryset = Ticket.objects.all().order_by('-id') serializer_class = TicketSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] def create(self, request): data = request.data print(data['titulo']) print(request.user) print(request.headers) c = Created() c.user = request.user c.save() V = Vendedor.objects.get(id=int(data['vendedor'])) print(V) T = Ticket() T.titulo = data['titulo'] T.estagio = Estagio.objects.get(id=int(data['estagio'])) T.cliente = Cliente.objects.get(id=int(data['cliente'])) T.org = Organizacao.objects.get(id=int(data['org'])) T.valorestimado = int(data['valorestimado']) T.termometro = data['termometro'] T.vendedor = V T.status = 'Aberto' T.created = c T.save() try: if data['obs'].length >= 1: for … -
How to display Django DayArchiveView by clicking on a Calendar cell?
I have a calendar that tracks orders. All calendar cells are interactive. My goal is to display a panel with orders for a specific day that user has clicked on a calendar. I have created the DayArchiveView: class OrderDayArchiveView(DayArchiveView): queryset = Order.objects.all() date_field = "create_date" allow_future = True The template: {% extends 'ocal/base.html' %} {% block content %} <h1>Orders for {{ day }}</h1> <ul> {% for order in object_list %} <li> <a href="/ocal/{{ order.id }}/detail">Order {{ order.id }} </a> {{ order.status_str }} </li> {% endfor %} </ul> {% endblock %} And the url: path('date/<int:year>/<str:month>/<int:day>/', OrderDayArchiveView.as_view(), name="order_archive_day"), In utils.py I have created Calendar class with the function formatday where I added a href attribute on td: def formatday(self, day, events): events_per_day = events.filter(create_date__day=day) d = '' for event in events_per_day: d += f'<li> <a href ="{event.status}" style ="background-color: #FFDCDC;">{event.status}</a>' if day != 0: return f"<td><a href=''><span class='date'>{day}</span><ul>{d}</ul></a></td>" return '<td></td>' My idea was to add appropriate value to href attribute in utils.py. The value should display the OrderDayArchiveView based on the cell that was clicked, but I don't know what value should that be. Also, I believe it's important to mention that this view should be displayed on the same page where … -
Django Custom Manager for Reverse Foreignkey Lookup
I'm using a custom Model-Manager for Soft-Deletion and want to do a reverse Foreignkey lookup. The Manager: class SoftDeletionQuerySet(QuerySet): def delete(self): return super(SoftDeletionQuerySet, self).update(deleted_at=timezone.now()) def hard_delete(self): return super(SoftDeletionQuerySet, self).delete() def alive(self): return self.filter(deleted_at=None) def dead(self): return self.exclude(deleted_at=None) class SoftDeletionManager(models.Manager): use_for_related_fields = True def __init__(self, *args, **kwargs): self.status = kwargs.pop("status", "all") super(SoftDeletionManager, self).__init__(*args, **kwargs) def get_queryset(self): if self.status == "alive": return SoftDeletionQuerySet(self.model).filter(deleted_at=None) elif self.status == "dead": return SoftDeletionQuerySet(self.model).exclude(deleted_at=None) else: return SoftDeletionQuerySet(self.model) def hard_delete(self): return self.get_queryset().hard_delete() class SoftDeletionModel(models.Model): deleted_at = models.DateTimeField(blank=True, null=True) objects = SoftDeletionManager(status="alive") dead_objects = SoftDeletionManager(status="dead") all_objects = SoftDeletionManager() class Meta: abstract = True def delete(self): self.deleted_at = timezone.now() self.save() def hard_delete(self): super(SoftDeletionModel, self).delete() Used for a Model: class Sowi(SoftDeletionModel): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) Now, for a given user, i want to get his user.sowi_set, but only those SoWi's which are 'alive'. The "normal" user.sowi_set also returns the Elements which are dead, i.e. which have a deleted_at value != None. How do I only get the alive objects? Thanks in Advance! -
What is the best / easiest way to integrate the Jupyter Notebook editor to a 3rd party website?
My friend and I are working on our pet project, a website for hosting algorithms that test sociological hypotheses and accumulate knowledge on sociology. We envision our site to be similar to Wikipedia with one exception: we want to present all the articles on the site in the form of Jupyter Notebooks. Our site engine is based on Django. Could you please tell me what is the best / easiest way to add the Jupyter Notebook editor to a 3rd party website? We understand that Jyputer runs on Tornado, that it is single-user, and we need to write a lot of the server logic. Our current understanding is to use the Jyputer Client to work with IPython, take the UI from Jupyter Lab, and write the server handlers ourselves. Could you please tell me if this is the right approach? What should we keep in mind? Is there an easier way to achieve our goal (for example, base our work on Jupyter Server instead of Jupyter Client)? We would like to focus on developing our site and keep compatibility with Jupyter as much as possible so that we can update / commit a change to the Jupyter project if it … -
Django 'object is not iterable' error when using get() method
get() method is not working in Django, I have a model BlogPost, when I try to fetch data from that model using get() method it shows Error : 'BlogPost' object is not iterable def blog_post_detail(request, slug): query = BlogPost.objects.get(slug=slug) template_name = 'blog/post.html' context = {'query': query} return render(request, template_name, context) But the same thing works using filter() method def blog_post_detail(request, slug): query = BlogPost.objects.filter(slug=slug) template_name = 'blog/post.html' context = {'query': query,} return render(request, template_name, context) Note: I have only one post in BlogPost -
PermissionError: [Errno 13] Permission denied - Python/Django Locallibrary
So I'm following this tutorial: https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Home_page Using this code in my urls.py: urlpatterns += [ path('catalog/', include('catalog.urls')), ] Throws me the error PermissionError: [Errno 13] Permission denied: '/home/jakoubu/django_projects/locallibrary/catalog/urls.py' Anyone knows what's up? I've searched the entire internet for answers...