Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django How to get a queryset from another queryset in a template
I want to filter a queryset that depends on another queryset that already depends on another queryset My models.py class Escola(models.Model): id = models.AutoField(db_column='ID', primary_key=True) nome = models.CharField(db_column='Nome', max_length=255, blank=True, null=True) class Inscrio(models.Model): id = models.AutoField(db_column='ID', primary_key=True) escolaid = models.ForeignKey(Escola, models.DO_NOTHING, db_column='EscolaID', blank=True, null=True) class Utilizador(AbstractBaseUser) id = models.AutoField(db_column='ID', primary_key=True) inscriçãoid = models.ForeignKey(Inscrio, models.DO_NOTHING, db_column='InscriçãoID', blank=True, null=True) email = models.CharField(db_column='Email', max_length=255, blank=True, null=True, unique=True) nome = models.CharField(db_column='Nome', max_length=255, blank=True, null=True) password = models.CharField(db_column='Password', max_length=500, default='pass'); USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' My views.py def view_forms(request): return render(request, "main/view_forms.html", {"escolas": Escola.objects.all(), }) I am doing {% for escola in escolas %} {% for inscrio in escola.inscrio_set.all %} {% for utilizador in inscrio.utilizador_set.all %} <tr> <td><center>{{inscrio.id}}</center></td> <td><center>{{escola.nome}}</center></td> <td><center>{{utilizador.id}}</center></td> {% endfor %} {% endfor %} {% endfor %} I am currently trying to get the Inscrio data from Escola. But when I try to get the Utlizador data from the Inscrio I get nothing. How can I do this? Thanks in advance -
Configure SSL (HTTPS) for my Django (Elastic Beanstalk) Backend API
I've been struggling the past week learning AWS to deploy my React - Django application to AWS. My react stack is successfully deployed to AWS Amplify, took no time at all. After deploying my Django stack to Elastic Beanstalk, I've stumbled on the following error: xhr.js:178 Mixed Content: The page at 'https://amplify.url' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://api.elasticbeanstalk.com/'. This request has been blocked; the content must be served over HTTPS. My question is, how do I configure https to my django eb application? I purchased a domain for my front-end, but do I also have to purchase a domain for my back-end api, or do I use a subdomain? I'm having trouble finding instructions for the best practices, and how to implement them. If anyone can give me advice for configuring my elastic beanstalk load balancer, that would be great, thanks so much! -
How to save multiple videos and images in Django Rest Framework?
I am creating a Django based web application, where Post Model will have multiple images and videos. I want to upload those multiple images in images model and videos in video model # models.py #Post Model class Post(models.Model): # Owner / user user = models.ForeignKey(to=User, on_delete=models.CASCADE) caption = models.CharField(max_length=64, verbose_name='Post Caption') body = models.CharField(max_length=1024, verbose_name='Post Body') def __str__(self): return self.user.email def get_author(self): return self.user.email class Image(models.Model): post = models.OneToOneField(to=Post, on_delete=models.CASCADE) image = models.ImageField() class Video(models.Model): post = models.OneToOneField(to=Post, on_delete=models.CASCADE) image = models.FileField() # serializers.py class PropertySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Property fields = '__all__' def create(self, validated_data): media_files = self.context.get('view').request.FILES post = Property.objects.create( **validated_data ) for file in media_files.values(): """ if file is video: then file will be saved in video model if file is image: then file will be saved in image model How to do it? """ And how to validate if files are only image or video. If someone post any other things except image or video then it will give validation error. Is there any good way to it? -
Why do html rendared emails not recognize cdn based css?
I would like to send a HTML email formatted with Materialize CSS in Django, can any one help me? -
Issue Collecting Static Files in my Heroku app using Django
Here are my Static Files in 'Settings.py': STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals()) When I run 'heroku run python manage.py collectstatic' I get '0 static files copied to '/app/staticfiles', 153 unmodified, 355 post-processed and I clearly have files in the static folder that need to get collected. It works just fine locally. am I missing something dumb? Thanks. -
Django Nested inline formset-- nested form does not save to DB, no errors thrown
We have a few nested inline formsets in an application. Ideally, the goal is to allow for dynamic and unlimited population of these fields so that users can add an arbitrary number of notes. The form renders, the JS calls are populating; however, I am not seeing the update on the nested from manager. This is my first Django project and I am not finding anything regarding what is causing the hang up. The Organization is saved in the DB, but the notes are not. Thanks in advance for any help Model.py: class Organization(models.Model): //irrelevant organization information// class OrganizationNote(AbstractNotes): note = models.TextField(blank=True) org = models.ForeignKey(Organization, on_delete=models.CASCADE,blank=True, null=True) modelforms.py: class OrganizationForm(AbstractBigThree): class Meta: model = custModels.Organization fields = '__all__' orgNoteFormSet = inlineformset_factory(custModels.Organization, custModels.OrganizationNote, form=OrganizationForm, extra=0) ModelView.py class OrganizationCreateView(CreateView, AbstractOrganizationView): def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) org_note_form = orgNoteFormSet() return self.render_to_response( self.get_context_data(form=form, org_note_form=org_note_form)) def get_context_data(self, **kwargs): data = super(OrganizationCreateView, self).get_context_data(**kwargs) if self.request.POST: data['notes'] = orgNoteFormSet(self.request.POST) else: data['notes'] = orgNoteFormSet() return data def form_valid(self, form): context = self.get_context_data() notes = context['notes'] with transaction.atomic(): self.object = form.save() if notes.is_valid(): notes.instance = self.object notes.save() return super(OrganizationCreateView, self).form_valid(form) def get_success_url(self): return '/portal' template: {% extends 'base.html' %} {% … -
Custom backend authenticate success without returning User object
I'm writing a backend to validate users based on tokens from AWS Cognito. Is it possible to write an authenticate() method for a backend that "succeeds" without returning a Django User object? For example: class CustomBackend(BaseBackend): def authenticate(self, request, username=None, password=None): if token_is_valid(request.COOKIES["nz_auth_jwt"]): # Success, let the user through else: # Failure, redirect to login page to get token from Cognito My understanding of "authenticate()" is that "success" is denoted by returning a User object, and failure by returning None. Can this work or do we need to make User objects based on the tokens so we have a User to return? -
Apply an AND filter on search results with Django
I have a django application where I maintain a list of products. Each product has a number of "categorizations" attached to it. I want to search the table of product and apply filters to that search, so that with each added filter, there are less and less products returned. The categorizations have a relationship to product. They way they are attached to products is a bit complicated, but here is the gist of it: class ProductCategorization(Categorization): """ A categorization value selected for a specific `Product` """ value = models.ForeignKey(ProductCategorizationValue, related_name="categorizations", on_delete=models.PROTECT) product = models.ForeignKey(Product, related_name="categorizations", on_delete=models.CASCADE) class ProductCategorizationValue(CategorizationValue): value = models.CharField(max_length=100) So you could imagine that you would search for all products that have a categorization with value "SHOES" as follows: Product.objects.filter(Q(categorizations__value__value="SHOES")) Now this is all fine. However, now I want to apply a second filter, so that I only get a list of products that are SHOES and BLACK. I have tried variations of the following but I keep getting an empty list instead of relevant products: Product.objects.filter(Q(categorizations__value__value="SHOES") & Q(categorizations__value__value="BLUE")) I know there is something strange going on behind the scenes when the SQL query is built, I just can't figure out how to structure my Django code. -
ValueError: Missing staticfiles manifest entry for for heroku app with S3 storage
After deploying my app to heroku and setting debug = false, I'm getting a server 500 error with the following in the logs: ValueError: Missing staticfiles manifest entry for images/favicon.ico I've tried running collectstatic on Heroku and I tried disabling it. I also added the AWS config variables according to the Heroku docs but still nothing. Also my ALLOWED HOSTS contains the correct app domain taken straight from the Heroku logs. All media and static files should be served from my S3 bucket so I shouldn't need staticfiles or Whitenoise middleware. Settings.py: import os import storages import django_heroku # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '***' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = (os.environ.get('DEBUG_VALUE') == 'True') #DEBUG = True ALLOWED_HOSTS = ['localhost', 'appname.herokuapp.com', 'appname.com'] # Application definition # NOTE: django_cleanup should be placed last in INSTALLED_APPS. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'taggit', 'storages', 'post.apps.PostConfig', 'ckeditor', 'sorl.thumbnail', 'django_cleanup.apps.CleanupConfig', ] 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 … -
How to join models in django serializers?
I'm trying to join two models, but I got wrong result. How to do it right? My models: class MoocherPage(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=False) name = models.CharField(max_length=48, unique=True, blank=False, null=False) bio = models.TextField(blank=False, null=False) class MoocherResource(models.Model): url = models.URLField(blank=False, null=False) moocher = models.ForeignKey(MoocherPage, on_delete=models.CASCADE) And serializers: class MoocherResourceSerializer(serializers.ModelSerializer): class Meta: model = MoocherResource fields = ('url') class MoocherPageSerializer(serializers.ModelSerializer): resources = MoocherResourceSerializer(many=True, read_only=True) class Meta: model = MoocherPage fields = ('name', 'bio', 'resources') depth = 1 I expected { "name": "KissofLove", "bio": "I'm the kiss of love and I collect money for all lovers of the world.", "resources": ["https://stackoverflow.com/users/KissofLove"] } But the resources was not included. When I change read_only=True to False in the nested serializer an error appears. AttributeError: Original exception text was: 'MoocherPage' object has no attribute 'resources'. -
Returning a function from a separate python file in django
I have a project that just creates a plot. The code to generates this plot is stored in theplot.py from a function called theplotfunction. What i am trying to do is to show this plot to the user by pressing a HTML button in my index.html but it is not loading. I have my theplot.py to create the plot: THEPLOT.PY: def theplotfunction(request): import matplotlib.pyplot as plt import numpy as np import io from django.shortcuts import render plt.plot(range(10)) fig = plt.gcf() buf = io.BytesIO() fig.savefig(buf,format='png') buf.seek(0) string = base64.b64encode(buf.read()) uri = urllib.parse.quote(string) return render(request, 'plot.html',{'data':uri}) I then link my url to go to a function in views.py. URLS.PY: path('plot', views.plot, name='plot'), Then the views.py plot function will go to the theplot.py to run the code to generate the plot. VIEWS.PY: `from .theplot import theplotfunction` def plot(request): return (theplotfunction) My index.html shows the connection to views function to be run INDEX.HTML: <input type="button" value="plot" onclick="window.open('plot')"> finally the plot.html is shown to the user and the graph is seen PLOT.HTML: <img src="data:image/png;base64,{{ data }}" alt="" height="250" ,width="250"> my problem is the I click the button to generate the plot i get a function' object has no attribute 'get' error. The code worked when … -
Django with vue js not recognizing post primary key
Views : from django.shortcuts import render from django.http import JsonResponse, HttpResponse from .models import Post from django.views.generic import DetailView def returningJSONData(request): sharedData = list(Post.objects.select_related().values()) return JsonResponse(sharedData, safe=False) def postView(request): return render(request, 'main/feeds.html') class postDetailView(DetailView): model = Post urls : urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path('json', views.returningJSONData, name='applicationPostData'), path('<pk>/', views.postDetailView.as_view(), name="details") ] template: {% extends 'main/base.html' %} {% block content %} <div id="root-app"> <div style="height: 100vh !important; padding-bottom: 8%" class="row"> <div style="height: 100% !important; overflow-y: scroll;" class="col-sm-3 extraCol"></div> <div style="height: 100% !important; overflow-y: scroll;" class="col-sm"> <div style="width: 100%;" v-for="post in postObjects" class="ui card"> <div class="content"> <div class="right floated meta">[[post.date_posted]]</div> <img class="ui avatar image" src="https://cdn.pixabay.com/photo/2017/08/30/12/45/girl-2696947_960_720.jpg"> [[post.author]] </div> <div class="image"> <img> </div> <div class="content"> <div class="header"><a class="text-dark" :href="{%url 'details' pk=post.id%}">[[post.title]]</a></div> <p class="description">[[post.description]]</p> <span class="right floated"> <i class="heart outline like icon"></i> 17 likes </span> <i class="comment icon"></i> 3 comments </div> <div class="extra content"> <div class="ui large transparent left icon input"> <i class="heart outline icon"></i> <input type="text" placeholder="Add Comment..."> </div> </div> </div> </div> <div style="overflow-y: hidden !important;" class="col-sm-4 extraCol"> <div style="width: 100%;" class="ui card"> <div class="content center aligned"> <img src="https://cdn.pixabay.com/photo/2017/08/30/12/45/girl-2696947_960_720.jpg" class="ui avatar image" alt=""> <p class="description">Username: {{request.user}}</p> <p class="description">Email: {{user.email}}</p> </div> <div class="extra content"> <div class="center aligned author"> <a class="btn btn-primary btn-block text-white" … -
Do Django Template Processors Mess with URLs?
In Django, I am trying to render a url to a template. However, this url is rendered differently depending on how it is called. In the view: url = request.build_absolute_uri() print(url) # returns http://127.0.0.1:8000/path/ raise Exception(url) # returns //localhost:8000/path/ print(url[0]) # returns h raise Exception(url[0]) # returns h In the template: {{ url }} <!-- returns //localhost:8000/path/ --> I feel like I am going crazy here. Do Django's template context processors contain a regular expression that specifically checks for urls and messes with them? -
Django showing models_app.Role.none on accessing objects of model based on many to many field
I am trying to get objects of a model named Course role which is a many to many field, but on printing the role of the current user I get models_app.role.None. I want a list of courses of the current user on the basis of role. I am able to get the list on basis of department but not on basis of role as the role of current user gives None type. My models_app is: class Department(models.Model): name = models.CharField(max_length=256,primary_key=True) organisation = models.ForeignKey(Organisation,on_delete=models.CASCADE) def __str__(self): return self.name class Role(models.Model): name = models.CharField(max_length=256,primary_key=True) department = models.ForeignKey(Department,on_delete=models.CASCADE) class Meta: order_with_respect_to = 'department' def __str__(self): return self.name class UserProfileInfo(models.Model): # Create relationship (don't inherit from User!) user = models.OneToOneField(User, on_delete=models.CASCADE) isInstructor = models.BooleanField(default=False) department = models.ForeignKey(Department,on_delete=models.CASCADE) role = models.ManyToManyField(Role) profile_picture = models.FileField(upload_to='static/profile_pic/'+str(time.time()),default='d.jpeg') address = models.TextField(max_length=256) city = models.TextField(max_length=256) contact = models.BigIntegerField() class Meta: order_with_respect_to = 'department' def __str__(self): return self.user.username class Course(models.Model): name = models.CharField(max_length=256) description = models.TextField() department = models.ManyToManyField(Department) role = models.ManyToManyField(Role) instructor = models.ForeignKey(User,on_delete=models.CASCADE) deadline = models.IntegerField(default=30,blank=True) mandatory = models.BooleanField(default=True) def __str__(self): return self.name My views.py is: from django.shortcuts import render from models_app.models import UserProfileInfo,Department,Role, Course, Lesson,Quiz,Question,Assignment # Create your views here. def home(request): current_user_profile = request.user.userprofileinfo current_user = request.user … -
Django: How to fix 'The QuerySet value for an exact lookup must be limited to one result using slicing.' error
I am attempting to make a simple query where I grab all "STATION_ROLE" objects with parameters Active and Deleated equal to True and False respectively. In doing so I trigger an error: "The QuerySet value for an exact lookup must be limited to one result using slicing." #Query station_roles = STATION_ROLE.objects.filter(Active__exact=True,Deleated__exact=False) #Model class STATION_ROLE(models.Model): S_ID = models.ForeignKey(STATION, null=True, verbose_name="Ground Station", on_delete=models.CASCADE) Type = models.IntegerField(blank=True, null=True, verbose_name="Role Type") Settings = models.TextField(max_length=100000, blank=True, null=True, verbose_name="Role Settings") Active = models.BooleanField(default=False, verbose_name="Active Flag") #Task Turned on Deleated = models.BooleanField(default=False, verbose_name="Deletion Flag") #Task is compleated or user deleated DeleatedBy = models.ForeignKey(User, blank=True, null=True, verbose_name="Deleted By", on_delete=models.CASCADE) Others have asked this question but under different circumstances. In one I saw, someone passed in a queryset into one of the filter parameters. I understand the error that case, as a queryset wouldn't make sense for a filter parameter in an exact lookup. In this case I am not passing any queryset. Another answer has them slice the result as follows: station_roles = STATION_ROLE.objects.filter(Active__exact=True,Deleated__exact=False)[0] While this eliminates my error, I do not want to limit the results of this query to one result. I want station_roles to be comprised of multiple STATION_ROLEs Why does Django want me to … -
how to filter by __in for another model objects list
hi i want to make a query between two models without having any connection i want to check if a name in Customer model is in User class ModelA(models.Model): name = models.CharField(max_length=20) #others how to make a query to filter by all names which already taken in User model i tried these user_name = User.objects.al() #and also this user_name = list(User.objects.all()) #also this user_name = User.objects.values() ModelA.objects.filter(name__in=user_name) i need to return all names which already taken in User model! none of them worked ? is there something else to achieve this goal? thanks -
Python Django: Getting output as "task object(1)" instead of actual value in model table
I am pretty new to django. I am trying to create a simple task management app and I created a class Taskdb in model.py. The problem I am facing that I am getting output like task object(1) instaed of actual value that I put in task field. Please look into my files below (model.py and view.py) and let me know where I am going wrong. Models.py from django.db import models from django.utils import timezone class Taskdb(models.Model): task = models.CharField(max_length = 30) priority = models.CharField(max_length = 30) completed = models.BooleanField(default=False) time_date = models.DateTimeField(default=timezone.now) def __str__(self): return "%s %s"%(self.task, self.completed) Views.py from django.shortcuts import render, redirect from .forms import UserRegisterForm from .models import Taskdb def home(request): return render(request, 'index.html') def task(request): all_items = Taskdb.objects.all() return render(request, 'task.html', {'all_items': all_items}) task.html {% extends 'base.html' %} {% block body %} <h2>My Task</h2> <h4>Welcome {{ user.username }}!</h4> <h3>Your task list.</h3> {% for task in all_items %} <p>{{ task }}</p> {% endfor %} {% endblock %} Output: Screen shot of Task.html web page admin site: Screen shot of admin site of the app -
Auto logoff after x minutes of inactivity Django
I've been able to auto logoff using: SESSION_SAVE_EVERY_REQUEST = True SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_AGE = 60 However, this does not consider moving your mouse or scrolling as activity. Thus, if the user is reading something it considers inactive. How can I implement it such that scrolling and moving the mouse is also considered activity? Thanks! -
matching query does not exist - Django
I am working on a registration page. I extended django's User model to add additional fields. I have two forms connected with OnetoOnefield. I am getting this error. DoesNotExist at /register/ Influencer matching query does not exist. I think what I am doing wrong is creating User and Influencer model at the same time. My models.py file: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Influencer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(blank=True, null=True) ig_url = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return f"{self.user.first_name} {self.user.last_name}" @receiver(post_save, sender=User) def create_influencer(sender, instance, created, **kwargs): if created: Influencer.objects.create(user=instance) @receiver(post_save, sender=User) def save_influencer(sender, instance, **kwargs): instance.influencer.save() My forms.py file: class UserForm(forms.ModelForm): class Meta: model = User fields = ('first_name', 'last_name', 'email') class InfluencerProfileForm(forms.ModelForm): class Meta: model = Influencer fields = ('bio', 'ig_url') My views.py file: def register(request): user_form = UserForm() profile_form = InfluencerProfileForm() if request.method == 'POST': user_form = UserForm(request.POST, instance=request.user) profile = Influencer.objects.get(user=request.user) profile_form = InfluencerProfileForm(request.POST, instance=profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, 'Your profile was successfully updated!') return redirect('settings:profile') else: messages.error(request, 'Please correct the error below.') return render(request, 'accounts/register.html', { 'user_form': user_form, 'profile_form': profile_form }) -
The 'image' attribute has no file associated with it. how i get uuserprofile
** the 'image' attribute has no file associated with it. Error How i get userprofile link in header template i didn't get userprofile link when i get link of use profile in post so i get successfully but same code use for get userprofile link in header template i unable how i get userprofile link can you helpp me** header.html {% for i in userpofile %} <img src="{{i.userImage.url}}" href="{%url 'userprofile' i.user %}" class="align-self-start img-responsiv img-circle tm-border " alt="..."> <a href="{%url 'userprofile' i.user %}" style="color: rgb(7, 6, 6)" >{{i.user}}</a>&nbsp {% endfor %} i used same code in postfeed.html its worked successfully postfeed.html {% for i in posts %} {% for x in userpofile %} <div class="container post_div" id="{{i.id}}"> <div class="card a mt-5"> <h5 class="card-header"> <img src="{{x.userImage.url}}" href="{%url 'userprofile' i.user %}" class="align-self-start img-responsiv img-circle tm-border " alt="..."> <a href="{%url 'userprofile' i.user %}" style="color: rgb(7, 6, 6)" >{{i.user}}</a>&nbsp {% endfor %} views.py def user_home(request): # messages.success(request,'login successfully') user = Following.objects.get(user=request.user) #following_obj of user followed_users = user.followed.all() posts = Post.objects.filter(user__in = followed_users).order_by('-pk') | Post.objects.filter(user = request.user).order_by('-pk') liked_ = [i for i in posts if Like.objects.filter(post = i, user = request.user)] userpofile=Profile.objects.filter(user=request.user) data = { 'posts':posts, "liked_post":liked_, "userpofile":userpofile, } return render(request,'userview/userhome.html' ,data) -
Django app crashing on Heroku with error code h10
I am a newbie in deployment on heroku and I am trying to deploy my Django application.But my application keeps crashing with error code H10.I have created Procfile web: gunicorn mywebsite.wsgi Below are my logs . I am failing to understand the reason for crash.Can someone please help me . 2020-06-24T18:14:37.525092+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=datascienceportfolio.herokuapp.com request_id=adb1a587-4955-4308- a51d- f0b9dbe0d0b4 fwd="157.39.11.45" dyno= connect= service= status=503 bytes= protocol=https 2020-06-24T18:14:38.275186+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=datascienceportfolio.herokuapp.com request_id=31bd9fef- 1a08- 4761-8b2f-5f4b20586752 fwd="157.39.11.45" dyno= connect= service= status=503 bytes= protocol=https 2020-06-24T18:14:54.412361+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=datascienceportfolio.herokuapp.com request_id=6dafa2ac-e889-41d7- 83e4- df67ba196f81 fwd="157.39.11.45" dyno= connect= service= status=503 bytes= protocol=https 2020-06-24T18:14:54.836423+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=datascienceportfolio.herokuapp.com request_id=8a942922- 990f- 494a-9772-471016ff65eb fwd="157.39.11.45" dyno= connect= service= status=503 bytes= protocol=https 2020-06-24T18:25:55.243336+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=datascienceportfolio.herokuapp.com request_id=edffebf9-6eba-466f- a7ae- f81e0f890cc0 fwd="157.39.11.45" dyno= connect= service= status=503 bytes= protocol=https 2020-06-24T18:25:56.256962+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=datascienceportfolio.herokuapp.com request_id=39e4537a- 4028-4664-87bf-eec99eab51b5 fwd="157.39.11.45" dyno= connect= service= status=503 bytes= protocol=https -
Django combining form entries by datetime
I've created a django project to track medications at work. Using modelformset factory, I've created a form that allows the user to document the amount of each medication on the same form. For example, Drug 1, Drug 2, and Drug 3 are all listed on the same form and the user needs to enter the total amount of mg for each drug. When submitted, the entry creates a separate database record for each drug with the same datetime. I have created a query page that lists all the entries. I would like for the query to combine all the entries that share the same datetime, but I cannot figure this out. Does anyone have any suggestions? Thanks so much. -
Django : Adding a new row in a table based on a foreign key value using serializers via POST method
I am very new to serializers. I have two models currently. models.py class ChatSession(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=False) staff = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=False) is_active = models.BooleanField(default=True) started_at = models.DateTimeField(default=timezone.now) closed_at = models.DateTimeField(default=timezone.now) class ChatMessages(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=False, related_name="my_messages") is_staff = models.BooleanField(null=False) message = models.TextField(null=False) message_types = [ ('image', 'Image'), ('video', 'Video'), ('text', 'Text'), ('audio', 'Audio'), ] message_type = models.CharField(max_length=100, choices=message_types, null=False, default='text') sent_at = models.DateTimeField(default=timezone.now) chat_session = models.ForeignKey(ChatSession,on_delete=models.CASCADE, null=False) serializers.py class ChatSerializer(serializers.ModelSerializer): def create(self, validated_data): return ChatMessages.objects.create(**validated_data) class Meta: model = ChatMessages fields = "__all__" class ChatSessionSerializer(serializers.ModelSerializer): class Meta: model = ChatSession fields = "__all__" views.py #For fetching all msgs of a user @authentication_classes((TokenAuthentication,)) @permission_classes((IsAuthenticated,)) class Chat(APIView): def get(self, request, *args, **kwargs): id = self.kwargs['user_id'] #id = request.user.id Chat = ChatMessages.objects.filter(user_id=id) serializer = ChatSerializer(Chat, many=True) return Response(serializer.data) @authentication_classes((TokenAuthentication,)) @permission_classes((IsAuthenticated,)) class ChatSessionMessages(APIView): def get(self, request, *args, **kwargs): id = kwargs['chat_session_id'] Messages = ChatMessages.objects.filter(chat_session=id) serializer = ChatSerializer(Messages, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): id = kwargs['chat_session_id'] *what should I add here???* When my URL hits chat/<chat_session_id>/ I want to add a message to that particular session. How to I specify the data in request body to have that chat session id column be filled with id from … -
Heroku static files loading faild Django
I'm trying to push my Django project to Heroku, but it isn't loading the staticfiles. I'm not able to fix the issue with static files and i dont know why. i have used whitenoise guide here: http://whitenoise.evans.io/en/stable/django.html# nothing seems to work, it was worked before so it's so wired. heres my code: urls.py from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('studentform.urls')), ] settings.py: import os import dj_database_url BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ENV = os.environ.get('ENV', 'DEVELOPMENT') # SECURITY WARNING: keep the secret key used in production secret! if ENV == 'PRODUCTION': SECRET_KEY = os.environ.get('SECRET_KEY') else: SECRET_KEY = 'MYSECRET' # SECURITY WARNING: don't run with debug turned on in production! if ENV == 'PRODUCTION': DEBUG = False else: DEBUG = True ALLOWED_HOSTS = ['*'] # ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'studentform', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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 = 'formmate.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 = 'formmate.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases … -
Django_filters Widget Customize
How Can I Customize Widgets in Django_filters? I tried To Did Like This But There its make Value in Select Field GoneImage When Adding Widget, and When i removed the widget the value is shown Image When Remove Widget, Sorry for my bad English, Thanks Before class CustomerOrderFilter(django_filters.FilterSet): product = django_filters.ChoiceFilter( widget=forms.Select(attrs={'class': 'form-control'})) status = django_filters.ChoiceFilter( widget=forms.Select(attrs={'class': 'form-control'})) class Meta: model = Order fields = '__all__' exclude = ('customer', 'date_created', 'updated',)