Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I make a field readonly after sending a Post Request in Django?
How can I make the start_date readonly after the Question is created? I have tried modifying the admin.py file but the date field is still editable, I got no idea how to can solve that This is the Question model class Question(models.Model): poll_question = models.CharField(max_length=255, blank=False) title = models.CharField(max_length=255, blank=True) start_date = models.DateTimeField('date published', blank=False,) def __str__(self): return self.poll_question def choices(self): if not hasattr(self, '_choices'): self._choices = self.choice_set.all() return self._choices This is the code I added in the admin.py file in order to make the start_date readonly after creation but there is still no change. class DateAdmin(admin.ModelAdmin): def get_readonly_fields(self, request, obj=None): if obj: return self.readonly_fields + ('start_date') else: return [] -
how to make a profile page in django with the information availiable in django allauth module?
I want to make a url as account/profile and add some form to make change for the user information. I have tiried avatar module but it didnot work. -
django.db.utils.OperationalError: no such table: quiz_gradingmodel
This occurred after running python manage.py makemigrations after a new model known as "gradingmodel" was added into models.py ---What I did before running makemigrations--- db.sqlite3 was deleted. migrations file was deleted. relevant pycache file was deleted. PS: after commenting out the newly added model, makemigrations seems to work, I'm not sure why this is happening. Any suggestions/ideas would be greatly appreciated :) -
Correct way to display images in ReactJS from Django static files
I am building an app using ReactJS, Django, Heroku and as my storage I am using Amazon S3. When I run python manage.py collectstatic everything works as it should. All my static files are uploaded to my bucket. However, until now, in my ReactJS code I had been referring to my static images this way: <img className={"some-class"} src={"staticfiles/images/image.png"}/> And, of course, on my local host this would work. However, this line will always try to load the asset from my local storage. What would be the correct way to refer to my S3 bucket files on production and keep refering to local storage when in development? These are my settings for production: # ... all the keys and etc. are there. AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # s3 public media settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'myApp.storage_backends.PublicMediaStorage' And this is for my local development: STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') .. and of course at the end: STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] My .css files are correctly being loaded from the S3 bucket. However, I … -
ORA-00001: unique constraint DJANGO ORACLE
By Sql Developer, I made an insert into and in my page django shows it correctly, but when I enter another value through the page, I get the error that the id already exists, because the record was entered from the developer not from django, how can I fix this? to do a bulk upload from developer? -
(DJANGO-ALLAUTH) Select a valid choice. google is not one of the available choices
I want to add a social app provider though Django admin/socialaccount/socialapp/add/. I keep getting the error below: Even though I have already specified the app provide in the settings.py as followed: SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'offline', } } } Having followed all the required steps in the docs, obtained client id and secret key https://django-allauth.readthedocs.io/en/latest/providers.html#google and I also have refreshed, cleared cache, run makemigrations and migrate many times but the field won't show 'google' as the option. Could you show me the way to solve this? Thank you! -
ValueError at /success Invalid address in django EmailMultiAlternatives
I want sent to multiple email but i got this raise ValueError('Invalid address "%s"' % addr) ValueError: Invalid address "['ex1@gmail.com', 'ex2@gmail.com', 'ex404@gmail.com']" email_id = ["ex1@gmail.com","ex2@gmail.com","ex404@gmail.com"] username = name email = email_id ######################### mail system #################################### htmly = get_template('email/Email.html') d = { 's_id' : s_id, 'username': username, 'tran_id' : tran_id, 'amount' : amount } subject, from_email, to = 'welcome', 'your_email@gmail.com', email html_content = htmly.render(d) msg = EmailMultiAlternatives(subject, html_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.send() -
Django query orderby
I'm trying to create a queryset in Django. My queries continue in the following order. But it doesn't implement the order_by operation. What is the problem? The first two queries are working all_products = Product.objects.filter(category=category.id) all_products = all_products.filter(price__gte=100) all_products = all_products.order_by('price') -
Can you select all exists in django?
I have been building an access manager to police API interactions in my application. I have a model which represents a User having Access to a given model instance, it looks like: class Permission(models.Model): user = models.ForeignKey(User) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') The access manager is aware of model hierarchies and can figure out that if you're trying to view or modify a given object type with a given ID, that it can check if you have permissions on it, or on a parent entity in the tree. It builds up Q objects, and hits the database asking if a relevant permission exists for the user. I have come to a new use case, where a particular entity has 2 parents in the tree, and I need the access manager to check that the user has permissions somewhere one both sides of the tree. Here is a (sanitised) Q object that I thought is what I needed: <Q: (AND: (OR: (AND: ('content_type', <ContentType: myapp | foo>), ('object_id', 676)), (AND: ('content_type', <ContentType: myapp | bar>), ('object_id', 634)), (AND: ('content_type', <ContentType: myapp | wibble>), ('object_id', 1)) ), (OR: (AND: ('content_type', <ContentType: myapp | foo>), ('object_id', 2)), … -
Adding a `unique_on` constraint to an annotation filter in Django
In Django, how do you use the filter attribute of the Sum() annotation to only calculate SUM on attributes which belong to a unique model? In the codeblock below, how can roi_avg be filtered in a way that I can describe only in this pseudocode: roi_avg = Sum(avg_field, filter= tweets_we_need + Q(tweets__twitter_calls__coin__id==Unique) avg_field = F('tweets__twitter_calls__roi_plus_year') tweets_we_need = (Q(tweets__created_at__date__lt=one_year_back) & ~Q(tweets__twitter_calls__roi_plus_year=None)) users = ( User.objects .annotate( roi_avg = Sum(avg_field, filter= tweets_we_need), calls_count = Count('tweets', filter = tweets_we_need), unique_coins = Count('tweets__twitter_calls__coin', filter = tweets_we_need, distinct=True) ) .exclude(roi_avg=None) .order_by("-roi_avg", "-unique_coins") ) -
Django - Combining Urls from different apps
I am fairly new to Django and I had a question regarding how to manage multiple django apps. I have an app that deals with user accounts which shows the profile page and dashboard of the user. However, I have another app called blogs where I want to show the blogs written by that user. What I basically want is to have a separate tab in the navbar that says "blogs" and when you click on the blogs it should go to the url "localhost:8000/user/blogs" not just localhost:8000/blogs. How can I go about combining the two apps in such a way? -
Django deployed on Heroku in admin gives error 500
I'm very new to python. I've deployed my beginners Django app to Heroku. Its my tutorial project. I this project I have Students, Group, Teachers app. Models are connected somehow. So there is only CRUD class-based view. When Im entering admin page its only Group is working and showing list of objects. Teachers and Group gives 500error. Through application home page everything works properly. -
How can I setup html template to render my views and OneToOne models in Django?
I am new to Django and I am building a practice project for my portfolio. I have 2 models in Django which will be accessed by users/supervisors and also overall views by admins/superusers. class Vacation(models.Model): vacation_id = models.AutoField(primary_key=True) request_date = models.DateField(auto_now_add=True) requestor = models.ForeignKey("Employee",on_delete=models.SET_NULL,null=True) start_date = models.DateField(null=True) end_date = models.DateField(null=True) objects = models.Manager() def __str__(self): return (f"{self.vacation_id}") pass class VacationApproval(models.Model): is_approved = models.BooleanField(default=False) approved_by = models.ForeignKey(Supervisor,on_delete=models.SET_NULL,blank=True,null=True) approved_date = models.DateField(null=True, blank=True) team = models.CharField(choices=TEAM_CHOICES, max_length=255) vacation_id = models.OneToOneField("Vacation",on_delete=models.CASCADE,null=True) objects=models.Manager() I am trying to render the approval onto an HTML template. <thead> <tr> <th>Vacation ID</th> <th>Request Date</th> <th>Requestor</th> <th>Start Date</th> <th>End Date</th> <th>Status</th> <th>Approved Date</th> </tr> </thead> <tbody> {% for vacation in vacations %} <tr> <td>{{ vacation.vacation_id}}</td> <td>{{ vacation.request_date }}</td> <td>{{ vacation.requestor }}</td> <td>{{ vacation.start_date }}</td> <td>{{ vacation.end_date }}</td> <td><span class="tag tag-success">{{ vacation.vacation_id.vacation_approvals.is_approved }}</span></td> <td>{{ approval.approved_date }}</td> </tr> {% endfor %} My view below will assign the models for rendering within my html template class VacationListView(ListView): template_name = "vacation_list.html" context_object_name='vacations' def get_queryset(self): user = self.request.user if user.is_superuser: queryset = Vacation.objects.all() print("Superuser") print(queryset) else: queryset = Vacation.objects.filter( requestor=user ) return queryset def get_context_data(self, **kwargs): user = self.request.user context = super(VacationListView,self).get_context_data(**kwargs) if user.is_organizer: queryset = VacationApproval.objects.filter( organization=user.userprofile, ) context['vacation_approvals'] = VacationApproval.objects.all() print(context) return context -
Django: ModelForm registration overwrites prevoius object
I have been trying to make my own project based on a project from Codecademy Django path. Where a vetoffice is used as an example. I'm currently working on building upon the base code provided, and added Forms. I'm currently trying to use ModelForms to register a new owner, and then display a list of all registered owners at the vetoffice. But when I register a new owner, the previous owner is seemingly overwritten, and only the new one is displayed. I'm quite new to writing Django, so my code will not be perfect. The owner model: class Owner(models.Model): #The Owner table, with OwnerID as primary key #Owner can own several pets """Create the Owner SQLite Table. Primary Key: OwnerID, used as Foreign Key for paitient Fields: first_name(String), last_name(string), phone(string(of numbers)) __str__ for easy coupling first and last name of owner. Function: has_multiple_pets reurns boolean True if owner have several pets registered with the Vet Office. """ ownerID = models.BigAutoField(primary_key=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) phone = models.CharField(max_length=30) def __str__(self): #Returns the first and last name of owner with whitespace between return self.first_name + " " + self.last_name def has_multiple_pets(self): '''Do Owner have multiple pets. Checks if a owner … -
image not getting displayed in django
I have a simple snippet that is trying to show the image frame that I saved in DB but the page is me nothing, images are not getting displayed at all <div class="row"> <h3>Captured images </h3> {% for image in images_frames %} <div class="col-md-4"> <h3> {{image.time_stamp}} </h3> <img src="{{ image.image_frame.url }}" class="image_frames" alt=""> </div> {% endfor %} </div> Model class ImageFrames(models.Model): time_stamp = models.DateTimeField(auto_now_add=True) image_frame = models.FileField(upload_to = 'camera_frames',null=True,blank=True,max_length=500) -
what is this error after 'python manage.py migrate' i don't understend?
models.py this is my model.py file i don't 'python manage.py migrat' understend what is this problem.... plz anyone answer if you need another file plz aksed me !!!!! class Myclabusers(models.Model): first_name = models.CharField('first_name', max_length=100 ,default='') last_name = models.CharField('last_name', max_length=100, default='') email = models.EmailField('user email',default='') def __str__(self): return self.first_name +' '+self.last_name class Venue(models.Model): name = models.CharField('venue name' , max_length=100) address = models.CharField('address' , max_length=500) zip_code = models.CharField('zip code' , max_length=20) phone = models.CharField('phone no.' , max_length=15) wab = models.URLField('url' , max_length=100,default='http://') email = models.EmailField('email' , max_length=30) venue_owner = models.IntegerField('venue_owner' , blank=False, default=1) def __str__(self): return self.name class Event(models.Model): event_name = models.CharField('event name' , max_length=100) event_date = models.DateField('event time' ) venue = models.ForeignKey(Venue, blank=True, null=True,on_delete=models.CASCADE) manager = models.ForeignKey(User,default=User, on_delete=models.SET_NULL,null=True) description = models.TextField(blank=True) attendens = models.ManyToManyField(Myclabusers, blank=True ) def __str__(self): return self.event_name + ' at '+ self.venue.name enter image see error description here -
graphene-django v2.0 depth validation
Is there any way I can validate the query depth with graphene-django 2.0? I've tried to use this suggested backend: from graphql.backend.core import GraphQLCoreBackend def measure_depth(selection_set, level=1): max_depth = level for field in selection_set.selections: if field.selection_set: new_depth = measure_depth(field.selection_set, level=level + 1) if new_depth > max_depth: max_depth = new_depth return max_depth class DepthAnalysisBackend(GraphQLCoreBackend): def document_from_string(self, schema, document_string): document = super().document_from_string(schema, document_string) ast = document.document_ast for definition in ast.definitions: # We are only interested in queries if definition.operation != 'query': continue depth = measure_depth(definition.selection_set) if depth > 3: # set your depth max here raise Exception('Query is too complex') return document url(r'^api', csrf_exempt(FileUploadGraphQLView.as_view( schema=schema, middleware=(middleware), backend=DepthAnalysisBackend()))), but it returns the error FileUploadGraphQLView() received an invalid keyword 'backend'. as_view only accepts arguments that are already attributes of the class. -
Django REST - send multiple querysets in one GET-Response
My view currently accepts a username and if the user exists it sends back a queryset of all entries in a Model, where the corresponding userid fits. The Model UserProject consists of a UserID and a ProjectID, both are references to their own tables. I would like to add the Project Model to the queryset. my view: class GetUserDataByNameView( APIView, ): def get(self, request, username): if User.objects.filter(username = username).exists(): uid = User.objects.get(username = username).id queryset = Userproject.objects.filter(user_id = uid) readSerializer = UserprojectSerializer(queryset, many = True) return Response(readSerializer.data) else: return Response({"status": "error", "data":"no user with this username"}, status = 200) the Response currently looks like this: [ { "id": 16, "created_at": "2021-10-20T16:05:03.757807Z", "updated_at": "2021-10-20T16:05:03.762307Z", "user": 3, "project": 50 }, { "id": 17, "created_at": "2021-10-20T16:27:59.938422Z", "updated_at": "2021-10-20T16:27:59.945439Z", "user": 3, "project": 51 #"projectname": (from ProjectID 51) #"projectDescriptor": #" other stuff from ProjectModel": } ] So how would I insert the fields for the current Project ? If I did some useless stuff in the code, please tell me. Newbie in Django -
How can I send user registration details from Django to a postgresql table
I've successfully migrated my database to postgresql, but the issue is I don't know how to send user registration/login details to my postgresql table, please any help is appreciated. -
Django MultiValueDictKeyError when updating a models field
In my models i have two imageFields. When i try to update only one of them, or just change another field in my models thru my 'Edit view' it throws the error MultiValueDictKeyError. Due to errors i had with the updating i opted to doing the saving manually in the Views. Wondering if that is what is causing the error. I can't see any errors in the logic or with the code itself. My Views: def editTrucks(request, pk): item = get_object_or_404(trucks, pk=pk) if request.method == "POST": form = trucksForms(request.POST or None, request.FILES or None, instance=item) data = request.POST if form.is_valid(): try: truck = trucks.objects.get(vin=data['vin']) truck.nickname = data['nickname'] truck.make = data['make'] truck.model = data['model'] truck.type = data['type'] truck.plate = data['plate'] truck.ezPass = data['ezPass'] truck.mileage = data['mileage'] truck.reportedProblem = data['reportedProblem'] truck.inspection = convert_date(data['inspection']) truck.registration = convert_date(data['registration']) truck.oilChange = data['oilChange'] truck.isMonitored = data['isMonitored'] truck.status = data['status'] truck.title = request.FILES['title'] truck.insurance_card = request.FILES['insurance_card'] truck.save() except FileNotFoundError: truck_info = trucks( nickname=data['nickname'], make=data['make'], model=data['model'], type=data['type'], plate=data['plate'], vin=data['vin'], ezPass=data['ezPass'], mileage=data['mileage'], reportedProblem=data['reportedProblem'], inspection=convert_date(data['inspection']), registration=convert_date(data['registration']), oilChange=data['oilChange'], isMonitored=data['isMonitored'], status=data['status'], title=request.FILES['title'], insurance_card=request.FILES['insurance_card'] ) truck_info.save() return redirect('index') else: form = trucksForms(instance=item) return render(request, 'Inventory/edit_items.html', {'form': form}) My Model: class trucks(models.Model): TYPE_CHOICES = (('Sedan', 'Sedan'), ('Pickup', 'Pickup'), ('SUV', 'SUV'), ('Flatbed', 'Flatbed')) MON_CHOICES = … -
Get all objects with today date, django
I have a model like this class Maca(models.Model): created_at = models.DateTimeField( auto_now_add=True ) Now I want in the views.py file to get all the entries that have created today I'm trying this Maca.objects.filter(created_at=datetime.today().date()) But this looks for the clock that object is created too. Can someone help me to select all entries that have been created today? Thanks in advance -
How to add a distinct() to an annotation filter on Django queryset?
roi_values_to_sum = (Q(trades__created_at__date__lt=one_year_back) & ~Q(trades__roi_plus_year=None)) roi_sum_field = f('roi_plus_year') users = ( User.objects .annotate( roi_sum = Sum(roi_sum_field, filter = roi_values_to_sum), .exclude(roi_sum=None) .order_by("-roi_sum") In the query above, I want to annotate roi_sum to the users I am getting, however I only want to sum distinct trade objects because the same trade object appears multiple times. How can I pass a distinct() to the filter= field so the roi_sum only adds up distinct objects? In the above example, trades are attached to users, and they have created_at dates. -
I am trying to create user in auth_user in Django but I am getting this error TypeError at /register/ set_password() missing 1 required
Hello I am trying to create user in auth_user in database but it is showing me a error The method I am using from django.contrib.auth.models import User user = Users.objects.get(username='myuser') user.set_password('mypassword') user.save() My views.py def registerpage(request): if request.method == 'POST': myusername = request.POST['name'] email = request.POST['email'] pass1 = request.POST['password1'] pass2 = request.POST['password2'] myuser = User.objects.get(username=myusername) User.set_password('pass1') myuser.name = myusername myuser.email = email myuser.password = pass1 myuser.save() return redirect('testlogin') The error that I am getting TypeError at /register/ set_password() missing 1 required positional argument: 'raw_password' I need help ! -
django models cyclic import
I have read some relevant posts on the issue on mutual imports (circular). I am working on a django app, here's how I run to an issue: I have two apps, first one articles, second one tags my article model have a many to many field, to indicate relevant tags: articles/models.py from django.db import models from tags.models import Tag class Article(models.Model): tags = models.ManyToManyField(Tag) however, in my tags app, I also need to import Article model to achieve the methods: tags/models.py from django.db import models from articles.models import Article # Create your models here. class Tag(models.Model): title = models.CharField(max_length=100) content = models.CharField(max_length=255) def getAritcleLength(): pass def getQuestionLength(): pass I usually use a module to combine those class definitions, normally won't run into issue according to method resolution order. However, in django the workflow we need to put classes into separated folders, I will be so glad for any suggestion. -
Access and modify Django DB without login in as superuser
I have a newbie question here. I'm currently working on a site where the user can add items to a model I created. The thing works fine if I'm logged in as super admin in the Django admin panel, but if I'm not, the CSRF verification doesn't work and I can't operate. Is this a "Debug: True" thing? Once I'm ready to production and turn debug off, will it work without login? Thanks!