Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to pass an object by url to serializer
I want to create an API that takes care of a site to list movies and make ratings of each movie. Kind of like a movie review. The problem I have is how to make the qualification, how could it be? I leave you the models that I have! class Movie(models.Model): """Movie model.""" title = models.CharField(max_length=250) image = models.ImageField( default='movies/images/default.jpg', upload_to='movies/images/', ) description = models.TextField(blank=True, null=True) duration = models.TimeField() director = models.CharField(max_length=100) rating = models.FloatField(null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): """Return title.""" return self.title class Rating(models.Model): """Movie rating model.""" movie = models.ForeignKey( Movie, on_delete=models.CASCADE, related_name='rated_movie' ) rating_user = models.ForeignKey( User, null=True, on_delete=models.SET_NULL, related_name='rating_user', ) comments = models.TextField(blank=True) rating = models.IntegerField(default=5) def __str__(self): """Return summary.""" return f'@{self.rating_user.username} rated {self.rating}: {self.movie}' The idea is that it is accessed through the url, e.g. api/v1/rate/1/ and the rating can be done with a comment and the score that is given. -
Heroku with whitenoise not serving django staticfiles
How do I get heroku to serve my static files on my django project? Ok, on a push to heroku, I get this message rlated to staticfiles: $ python manage.py collectstatic --noinput remote: 130 static files copied to '/tmp/build_48c64d55/staticfiles', 410 post-processed. But when I go to my site, clear static files not being recognized and Network tab shows me: GET https://pure-everglades-09529.herokuapp.com/static/style.css 404 Not Found This is the content of my html referencing the css I cannot find: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="{% static 'style.css' %}"> <title>{% block title %}My amazing site{% endblock %}</title> </head> Here is the bottom of my settings.py which is configured just like everywhere says it should be like: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, 'static'), ] # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Activate Django-Heroku. django_heroku.settings(locals()) Here is higher up in my settings, I have added whitenoise dependencies as recommended everywhere: INSTALLED_APPS = [ 'myapp.apps.MyappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', # Disable Django's own staticfiles handling in favour of WhiteNoise, for # … -
How to provide user types while registering as a user using google in Django rest framework
I have a customeuser model which inherits from AbstractUser. I have also used sign-up using google feature. But now later in my project, I have to add user types. For eg user can be owner,manager and staff and they have their own privileges. My model: ROLE = (('owner','OWNER'),('manager','MANAGER'),('staff','STAFF')) class User(AbstractUser): SOCIAL_AUTH_PROVIDERS = ( ("GOOGLE", ("GOOGLE")), ("FACEBOOK", ("FACEBOOK")), ("TWITTER", ("TWITTER")), ) name = CharField(_("Name of User"), blank=True, max_length=255) email = EmailField(_("Email Address"), unique=True) mobile = CharField( _("Mobile Number"), max_length=16, unique=True, blank=True, null=True ) email_verified = BooleanField(default=False) social_auth = CharField( choices=SOCIAL_AUTH_PROVIDERS, max_length=100, blank=True, null=True, ) role = models.CharField(max_length=15, choices=ROLE, default='staff') #added this field later first_name = None last_name = None username = None USERNAME_FIELD = "email" REQUIRED_FIELDS = [] objects = CustomUserManager() Here I migrated a new field role to the user model because I needed it because of business requirements. The change in my serializer will be like this. class UserRegisterationSerializer(serializers.ModelSerializer): def validate(self, data): email = data["email"] password = data.get("password") role = data["role"] #added this part mesg = "This email has been already registered." if User.objects.filter(email=email).exists(): raise serializers.ValidationError({"email": mesg}) if password: user = User(email=email,role=role) #added role here too try: validate_password(password=password, user=user) except Exception as e: raise serializers.ValidationError({"password": e.messages}) return data Here … -
Latest() function gives, addPost(ModelName) matching query does not exist error
I had an object that their id was 47(this was a latest object) so latest() method was giving me the correct result but when i deleted the object that their id had 47, now my latest object is that, which id has 46.. When i am trying to get the latest object it raise error matching query does not exist.. it should give me the latest object.. models.py from django.db import models from datetime import datetime # Create your models here. class addPost(models.Model): postId = models.AutoField(primary_key=True) title = models.CharField(max_length=100) category = models.CharField(max_length=60) image = models.ImageField(upload_to="blog/images", default="") content = models.TextField(default="") date = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = "date" views.py def index(request): obj = addPost.objects.all().latest() print(obj.postId) -
Running Django tests without collect static
I am trying to run a test suite for django that uses inlinecss. inlinecss references a static file in the template as follows: {% load inlinecss %} {% inlinecss "css/emails/base.css" %} When running in Debug mode this works fine, when running in production (having run collectstatic) this also works fine. However when running tests (without running collectstatic before) I get the following: FileNotFoundError: [Errno 2] No such file or directory: '/app/project-name/staticfiles/css/emails/base.css' This makes sense as django is looking for the file in STATIC_ROOT (STATIC_ROOT = os.path.normpath(join(os.path.dirname(BASE_DIR), "staticfiles"))) I am wondering if there is a way to allow Django to access this file without having to run collectstatic? It would be ideal if I could add some settings to test.py so that it could collectstatic to a tmp directory or not require collectstatic at all (like when running in debug mode) but I have had no success trying this. I am using pytest to run tests. -
Show folium map received in django JsonResponse using javascript
I am sending a folium map through django JsonResponse. While rendering, I just can't make it show the map. I am using d3.js. I just don't understand how to add a '|safe' equivalent action. Here is my view: def show_map(tuple_lat_lon, name): start_coords = tuple_lat_lon[0] folium_map = folium.Map( location=start_coords, zoom_start=14 ) folium.CircleMarker( tuple_lat_lon[0], radius=8, popup=name, color='#3186cc', fill=True, fill_color='#3186cc' ).add_to(folium_map) folium.Polygon(tuple_lat_lon).add_to(folium_map) buffer = io.BytesIO() plt.savefig(buffer, format='png') buffer.seek(0) image_png = buffer.getvalue() buffer.close() graphic = base64.b64encode(image_png) graphic = graphic.decode('utf-8') return graphic farm_map = show_map(tuple_lat_lon, 'MyMap') return JsonResponse({ 'farm_map':farm_map, }) Here is my d3.js code: var farm_map = block_details_response['farm_map']; d3.select('#block_map').append('img').attr('src', farm_map); here is the html: <div id="block_map"></div> I can see when I inspect html, the image code...but not the image. So I want to know: Is it a good idea to send folium map in response? I did it cause I call a lot of my own apis on the web page. As tutorials suggest, this the way to show the map:{{ farm_map | safe }} . I can't do that since I am using d3.js . Essentially javascript. I tried d3.select('#block_map').append('img').attr('src', farm_map + '|safe'). Did not work. Any ideas suggestions are welcome -
Get a javascript element by ID from select and pass to Django url
I have select options and I want to send the value to a url offside the form (because I'm using a image as a link). html: <form action="" method="GET" id="maintenanceForm"> <div class="form-group col-md-4"> <label for="assigned" style="font-size:medium;">Assigned</label> <select class="form-control" id="assigned" name="assigned"> <option value=""></option> <option value="a.takao">André Takao</option> <option value="adam.m">Adam William</option> <option value="alex.matos">Alex Matos</option> </select> </div> </form> <a href="{% url 'maintenance_issue_validation_approved' %}?id={{ maintenance_issue.id }}&assigned=assigned"> <img src="{% static 'images/icons/approved.png' %}"> </a> <script> var assigned = document.getElementById('assigned').value; return assigned; </script> views: def maintenance_issue_validation_approved(request): if request.method == 'GET': issue_id = request.GET.get('id') assigned = request.GET.get('assigned') print(assigned) How to get the "assigned" select value and send it to my view? The expected value is, print the selected assigned value: for example: adam.m -
Django ORM filter logic for foreign key is giving unclear results
I have following two query set as properties of django model 1 - Comment.objects.filter(ForeignKeyField=self) 2 - Comment.objects.filter(ForeginKeyField=self.id) I am not why both these lines are giving same result , namely CommentObjectList ? Why I am able to filter the Comment Resultset with self and self.id both ?? -
How to pad a dataframe with values similar to rjust for string
I have a Table with structure like [qtr_dates, sales]. I have created a QuerySet from that table. qtr_dates are end date of each quarter month (i.e. 31st March, 30th June, 30th Sept, 31st Dec). Then I am doing something like this qs = qs.filter(qtr_dates__range=[(running_qtr_date - relativedelta(years=9), running_qtr_date]) df = qs.to_dataframe() Since I am using a range of 36 quarters date range, my expectaiton would be to get a df of 36 rows. But for some filter criteria if this comes out as say 20 rows, I want to pad the dataframe with missing quarter dates and sales as 0. How to do that? -
Django & Gunicorn: ModuleNotFoundError when running gunicorn
I followed a tutorial to dockerise a Django app, but I'm having trouble applying the same instructions to my own app. My folder structure looks like this: ├── project_name │ ├── app_name │ │ ├── admin.py │ │ ├── apps.py │ │ ├── exceptions.py │ │ ├── forms.py │ │ ├── functions.py │ │ ├── __init__.py │ │ ├── migrations │ │ ├── models.py │ │ ├── __pycache__ │ │ ├── report_functions.py │ │ ├── static │ │ ├── templates │ │ ├── tests.py │ │ ├── upload_file.py │ │ ├── urls.py │ │ └── views.py │ ├── project_name │ │ ├── asgi.py │ │ ├── __init__.py │ │ ├── __pycache__ │ │ ├── settings.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── db.sqlite3 │ ├── manage.py │ └── static │ ├── admin │ └── app_name ├── Dockerfile ├── nginx.default ├── pip_cache ├── requirements.txt ├── start-server.sh └── venv start-server.sh #!/usr/bin/env bash # start-server.sh if [ -n "$DJANGO_SUPERUSER_USERNAME" ] && [ -n "$DJANGO_SUPERUSER_PASSWORD" ] ; then (python3 manage.py createsuperuser --no-input) fi (cd project_name; gunicorn project_name.wsgi --user www-data --bind 0.0.0.0:8010 --workers 3) & nginx -g "daemon off;" project_name/project_name/wsgi.py """ WSGI config for creativ_ceutical project. It exposes the WSGI callable as … -
How would I display the actual item and not its ID in Django forms?
I have a form whose details are displayed. I have a field that is read-only [book_id] but it is the ID that is displayed. How would I have it display the actual item??? class IssueForm(forms.ModelForm): def __init__(self,*args, pk,school,issuer, **kwargs): super(NewIssueForm, self).__init__(*args, **kwargs) klasses = [1,2,3,4] if Books.objects.filter(school=school,id=pk,subject__name = "revision"): self.fields['due_days'].widget.attrs['hidden'] = False else: self.fields['due_days'].widget.attrs['hidden'] = True self.fields['issuer'].initial = issuer self.fields['borrower_id'].queryset = Student.objects.filter(school=school,klass__name__in = klasses) self.fields['borrower_id'].label = "Select Student." self.fields['book_id'].label = "Selected Book." self.fields['book_id'].widget.attrs["readonly"] = True self.initial['book_id'] = Books.objects.get(school=school,id=pk) class Meta: model = Issue fields = ['issuer','book_id','borrower_id','due_days'] widgets = { 'book_id':forms.TextInput(attrs={"class":'form-control','type':''}), 'issuer':forms.TextInput(attrs={"class":'form-control','type':'hidden'}), 'borrower_id': Select2Widget(attrs={'data-placeholder': 'Select Student','style':'width:100%','class':'form-control'}), 'due_days':forms.TextInput(attrs={"class":"form-control"}), } -
How do I update only selected records in the Django queryset?
Immediately I apologize for the mistakes, English is not my native language (this text is google translation) Hello I am new to django and I have a question. I have a table in DB with fields and boolean value "checked". You need to give access to check records to other users, and I would not want to give access to the admin panel. How can I show a checkbox in a view along with a queryset in the table to set the value to true in the table and update only the rows selected by this checkbox? P.S. I tried through the form but it only creates a new record p.p.s Now it turns out only to update ALL records of the table Here is my model.py class moneIn(models.Model): date = models.DateTimeField(auto_now_add=True, verbose_name='') dateUpdate = models.DateTimeField(auto_now=True) ts = models.IntegerField(verbose_name='') pl = models.IntegerField(verbose_name='') rem = models.IntegerField(verbose_name='') comment = models.TextField(max_length=200, verbose_name='', blank=True) staffer = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='') checked = models.BooleanField(verbose_name='', default=False) checkedUser = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name='', blank=True, null=True, related_name='checkedUser') def __str__(self): return '{0}'.format(self.date) # return self.user class Meta: ordering = ['-date'] verbose_name = '' verbose_name_plural = '' You need to change the "checked" parameter through the template and automatically insert the user … -
CORS error with React native web with Nginx + Django
I've faced CORS error with EC2 Django + Nginx server. Have no idea why it never works. Error: Access to fetch at 'https://serveraddress/api/v1/user' from origin 'http://localhost:19006' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. How I requestsed fetch(`https://${env.apiUrl}/api/v1/user`, { method: "GET", mode: "cors", withCredentials: true, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept", "Access-Control-Allow-Methods":"GET,PUT,POST,DELETE,OPTIONS", "Access-Control-Allow-Credentials":'true', Authorization: await getToken(), }, Also tried with using Authorization header or request get, post request auth is not requried, but none of them worked. Plus, tried with axios, xmlhttprequest and none of them worked.. Followings are settings for Nginx + Django Nginx Settings location / { proxy_hide_header Access-Control-Allow-Origin; add_header Access-Control-Allow-Origin '*'; add_header Access-Control-Allow-Credentials true always; proxy_pass http://web/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; Django Settings All the settings for cors including django-cors-headers middleware and put corsheaders.middleware.CorsMiddleware on the top of it. MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', .... ] CORS_ORIGIN_ALLOW_ALL = True ALLOWED_HOSTS = ['*'] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ 'DELETE', 'GET', … -
user automatically logged out after payment is done on redirect from bank
so i have this problem that when user make a payment and redirect to the website, the user is no longer logged in, im new in django and i dont know what is the problem and how to solve it. this is the function that i downloaded from the bank website. @csrf_exempt def payment_return(request): if request.method == 'POST': pid = request.POST.get('id') status = request.POST.get('status') pidtrack = request.POST.get('track_id') order_id = request.POST.get('order_id') amount = request.POST.get('amount') card = request.POST.get('card_no') date = request.POST.get('date') if Payment.objects.filter(order_id=order_id, payment_id=pid, amount=amount, status=1).count() == 1: idpay_payment = payment_init() payment = Payment.objects.get(payment_id=pid, amount=amount) payment.status = status payment.date = str(date) payment.card_number = card payment.idpay_track_id = pidtrack payment.save() if str(status) == '10': result = idpay_payment.verify(pid, payment.order_id) if 'status' in result: payment.status = result['status'] payment.bank_track_id = result['payment']['track_id'] payment.save() return render(request, 'accounts/profile.html', {'txt': result['message']}) else: txt = result['message'] else: txt = "Error Code : " + str(status) + " | " + "Description : " + idpay_payment.get_status(status) else: txt = "Order Not Found" else: txt = "Bad Request" return render(request, 'error.html', {'txt': txt}) def payment_check(request, pk): payment = Payment.objects.get(pk=pk) idpay_payment = payment_init() result = idpay_payment.inquiry(payment.payment_id, payment.order_id) if 'status' in result: payment.status = result['status'] payment.idpay_track_id = result['track_id'] payment.bank_track_id = result['payment']['track_id'] payment.card_number = result['payment']['card_no'] payment.date = … -
Django secondary admin site links to main admin site
I'm trying to add a secondary admin site and it's working correctly except that any links are pointing to the main admin site. Not sure how to get around this. If I visit /dispatch/admin/ the model Run is visible but when I click the link it directs me to /admin/dispatch/run/ instead of /dispatch/admin/dispatch/run/. Django==3.2.7 class DispatchAdminSite(admin.AdminSite): pass class DispatchRunAdmin(RunAdmin): def get_queryset(self, request): return ( super().get_queryset(request) .filter_today_or_future() ) def get_readonly_fields(self, request, obj=None): return [f.name for f in self.model._meta.fields] dispatch_admin_site = DispatchAdminSite(name='Dispatch') dispatch_admin_site.register(models.Run, DispatchRunAdmin) dispatch/urls.py app_name = 'dispatch' urlpatterns = [ path('admin/', admin.dispatch_admin_site.urls), ] project/urls.py urlpatterns = [ path('dispatch/', include('dispatch.urls')), path('admin/', admin.site.urls), ] -
Funciones en Paralelo con Django y Python
Estoy desarrollando una aplicación web con Python en Django 3.2.7. Resulta que he generado un script que ejecuta una automatización. En la interfaz, pido por formulario la cantidad de veces que dicha automatización se tiene que ejecutar. Este es mi forms.py don pido la automatización a ejecutar y la cantidad de veces que corre: class Task_Form(forms.Form): TASKS = (("1", "Catalina"), ("2", "Nosis"),) task = forms.ChoiceField(choices = TASKS, widget=forms.Select(attrs={'class': 'form-select'})) number_processes = forms.IntegerField(widget=forms.NumberInput({ 'class': 'form-control', 'placeholder': '1' })) Resulta que en el back, en las views.py tengo lo siguiente: def load_task(request): """Renders the test page.""" assert isinstance(request, HttpRequest) if request.method == 'POST': form = forms.Task_Form(request.POST, request.FILES) if form.is_valid(): select = form.cleaned_data['task'] number_processes = form.cleaned_data['number_processes'] if select == '1': for i in range(number_processes): catalina.start() else: form = forms.Task_Form() return render(request,'app/loadfile.html', { 'form': form, 'title': 'Load File',}) Donde genero un bucle for que va a dar vueltas una x cantidad de veces dependiendo el número que ponga el usuario. El problema es que esto se ejecuta de forma síncrona, por lo que hasta que no termine la función catalina.start() la primera vuelta del for, no voy a poder pasar a la segunda. Necesito que independientemente de que termine o no de ejecutar Catalina.start() … -
ezdxf in django- not writing to file, or not functioning
I'm currently in the middle of creating a web app using Django and ezdxf. the end goal is to output the contents of the dxf file both as a dxf file and as a png. This seems like a beginner django question and intermediate ezdxf question. I wrote a set of instructions for ezdxf that instantiate a file, then draw my artwork, and then saves the file as both a .dxf and as a png. This works great in the command line of pycharm. def instantiate_drawing(): """starts a new drawing and adds all needed layers etc.""" doc = ezdxf.new('R2010', setup=True) msp = doc.modelspace() lines_layer = doc.layers.new('python-lines', dxfattribs={'color': 0}) dims_layer = doc.layers.new('python-dims', dxfattribs={'color': 3}) label_layer = doc.layers.new('python-label', dxfattribs={'color': 13}) myStandard = doc.styles.new('myStandard', dxfattribs={'font': 'Helvetica.ttf'}) blocdoc = ezdxf.readfile('block_library.dxf') blocmsp = blocdoc.modelspace() importer = Importer(blocdoc, doc) return doc, msp, lines_layer, dims_layer, label_layer, myStandard, blocdoc, importer example drawing instructions def create_rectangle(pt0, pt1, off=3, dims=None): """creates a rectangle between 2 points, and adds dims between take two tuples with pt coords, higer coords second""" width, height = pt1[0] - pt0[0], pt1[1] - pt0[1] lineweight = 5 msp.add_lwpolyline([(pt0[0], pt0[1]), (pt1[0], pt0[1]), (pt1[0], pt1[1]), (pt0[0], pt1[1]), (pt0[0], pt0[1])], dxfattribs={'layer': 'python-lines'}) # rectangle if dims: dimw = msp.add_linear_dim(base=(pt0[0], … -
Django Web App Music Player Not Playing .mp3 files or showing .img files
I am building a music player as a web app using Python, Django, and postgres. I have a few albums I am working with that are stored in the database. All of my database imports are working properly. My css script is working. Front end is connected to backend and the music player looks good. In the browser, each page accurately paginates through each song in a given album, displaying artist name, album title, track title, track number. This suggests the correct information is being supplied from the database. All the necessary buttons are present but when I click on play nothing happens and the album artwork does not display. I have spent time troubleshooting this but have been unsuccessful in tracking down where the python code isn't connecting correctly to the JS/HTML/CSS code. I have one app that deals with the database layer - import scripts, etc. The musicplayer app contains the rest of the code. Setup: settings.py PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static') ] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' urls.py from django.urls import path, include from django.conf import settings from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib.staticfiles.urls import static urlpatterns = [ path('admin/', … -
My django app url reversing is not working
I have a web application which I have split into several applications. I think this might have been an over exageration on my part but regardless I want to make this work and understand what my problem is. To those apps I have a list of buttons with the links: <li class="nav-item active"><a class="nav-link" href="{% url 'dashboard' %}"><i class="fa fa-home"></i><span class="link-text">Home</span></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'resume:index' %}"><i class="fa fa-user"></i><span class="link-text">Resume</span></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'services:index' %}"><i class="fa fa-rocket"></i><span class="link-text">Services</span></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'portfolio:index' %}"><i class="fa fa-briefcase"></i><span class="link-text">Portfolio</span></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'blog:index' %}"><i class="fa fa-pencil"></i><span class="link-text">Blog</span></a></li> <li class="nav-item"><a class="nav-link" href="{% url 'contact:index' %}"><i class="fa fa-address-book"></i><span class="link-text">Contact</span></a></li> The urls for these are stored in the webapp/urls.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('dashboard.urls')), path('resume/', include('resume.urls')), path('portfolio/', include('portfolio.urls')), path('articles/', include('articles.urls')), path('blog/', include('blog.urls')), path('services/', include('services.urls')), path('contact/', include('contact.urls')) ] And in each webapp/app/urls.py file I have the urlpatterns as such: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ] Currently I am having two issues with this. The dashboard link does not work and I get the error "No reverse match for 'dashboard' … -
Django: Filter based on foreignkey's start date and end date
I have the following two models: class ParentModel(models.model): name = models.CharField("Name", max_length = 256, blank = True) start_date = models.DateField(blank = True, null = True) end_date = models.DateField(blank = True, null = True) class ChildModel(models.model): name = models.CharField("Name", max_length = 256, blank = True) parent_model = models.ForeignKey(ParentModel, blank = True, null = True, on_delete=models.SET_NULL) start_date = models.DateField(blank = True, null = True) end_date = models.DateField(blank = True, null = True) Now I want to filter all the childmodel's whose date range is not within the date range of the associated parentmodel's date range. The code I tried: import pandas as pd child_models = ChildModel.objects.filter(start_date__lte=input_end_date, end_date__gte=input_start_date) exceeding_child_models = [] for child_model in child_models: date_range = pd.date_range(start=child_model.start_date, end=child_model.end_date) if child_model.start_date not in date_range or child_model.end_date not in date_range: exceeding_child_models.append(child_model) How can I do that using Django ORM in a single query? -
Django REST on LAMP - default /admin not always showing app with its models
I am pretty new to the Django + REST Framework and I was trying to just show some models on the admin page. However, when loading the admin-page in the browser it was just the default site with users and groups. When i reload the page, sometimes it is showing my app and models but not always. in a second tab, the models are shown at the same time as the other one that makes me think its some kind of server problem itself. What i did is this: start an app, python manage.py startapp testapp register in settings.py, in the app folder: models.py: from django.db import models class Book(models.Model): prename = models.CharField(max_length=150) lastname = models.CharField(max_length=150) admin.py: from django.contrib import admin from .models import Book admin.site.register(Book) migrate the model python manage.py migrate python manage.py makemigrations python manage.py migrate -
how to upload more than 2 images from a Forms.py form without error?
*Good evening dear web developer, I have a problem with django 3.2.8. I configured my settings normally for media files. When I fill out the form from the django administration interface, the image is stored friends when I go through the form, it shows me "Page not found (404), Raised by: django.views.static.serve" -
How to define a URL to a css stylesheet for TinyMCE in Django
I want to render the TinyMCE widget with a custom stylesheet. Therefor I somehow need to build the url to that stylesheet so I can pass it to the widget. # Form from poller import settings class PollersForm(forms.Form): tinymce_css_url = str(settings.BASE_DIR) + str(settings.STATIC_URL) + 'css/about.css' print(tinymce_css_url) # Returns /Users/jonas/PycharmProjects/poller/static/css/about.css # Form poller_category = forms.ModelChoiceField(widget=forms.RadioSelect(attrs={ 'class': 'poller-category-radio', 'content_css': tinymce_css_url }), queryset=Category.objects.all().order_by('category'), label='Select a Category', required=True) My issues are that the stylesheet isn't loaded when rendering the template and I'm not sure if this would also work for production without any further changes? -
__str__ returned non-string (type NoneType) | Django [closed]
ERROR TypeError at /barteradmin/adminusers __str__ returned non-string (type NoneType) Request Method: GET Request URL: http://127.0.0.1:8000/barteradmin/adminusers Django Version: 3.2.6 Exception Type: TypeError Exception Value: __str__ returned non-string (type NoneType) Exception Location: C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\db\models\base.py, line 521, in __repr__ Python Executable: C:\Users\Qasim Iftikhar\anaconda3\python.exe Python Version: 3.8.5 Python Path: ['C:\\xampp\\htdocs\\Projects\\Barter', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\python38.zip', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\DLLs', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib', 'C:\\Users\\Qasim Iftikhar\\anaconda3', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\Pythonwin'] Server time: Wed, 06 Oct 2021 15:10:36 +0000 CODE # Weekly Users currenttime_non_string = datetime.now() currenttime = currenttime_non_string.isoformat() currenttime2 = datetime.now() thisweek_non_string = currenttime2 - timedelta(days=7) thisweek = thisweek_non_string.isoformat() weeklyusers = BarterUserDetail.objects.filter(user_registration_date__gte = thisweek) & BarterUserDetail.objects.filter(user_registration_date__lte = currenttime) print("Printing Dates") print(currenttime, type(currenttime) , yesterday, type(yesterday), thisweek, type(thisweek)) print(dailyusers, weeklyusers) CODE EXPLANATION Trying to get records from database of last seven days. Having error at printing the records whether in python or in django templates. -
How To Fix The view loginapp.views.login didn't return an HttpResponse object. It returned None instead. in django
Hello I'm Creating Login Form In Django. How Got an error > The view loginapp.views.login didn't return an HttpResponse object. It > returned None instead. in django my code: def login(request): if request.method=="POST": username=request.POST['username'] password=request.POST['password'] user = authenticate(request, username=username, password=password) else: return render(request, "registration/login.html")