Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django initial migrate of existing Application
I have an application with everything working on local dev machine, and I am trying to set it up on another dev machine with fresh DB (Postgres). I wasnt able to run migrations due to a cannot find field error, so i removed all migrations and tried to make them again, but same error. django.db.utils.ProgrammingError: relation "questionnaire_projectquestionanswerchoice" does not exist LINE 1: ...rojectquestionanswerchoice"."id") AS "count" FROM "questionn... So it seems that makemigrations checks code for issues before it makes them, and obviously it wont find them and always errors. The culprit is below, and commenting out, then doing the migrations works but is a bit of a hack, so if i ever need to do again i would have to follow same process. I have left the culprit commented below. This code works, and then i have to uncomment after. Is there an official way to handle this? class ProjectQuestionMostUsedAnswerChoiceViewset(viewsets.ModelViewSet): # dupes = ( # models.ProjectQuestionAnswerChoice.objects.values("name") # .annotate(count=Count("id")) # .order_by("-count") # .filter(count__gt=0)[:10] # ) # queryset = ( # models.ProjectQuestionAnswerChoice.objects.filter( # name__in=[item["name"] for item in dupes] # ) # .distinct("name") # .order_by("name") # ) queryset = models.ProjectQuestionAnswerChoice.objects.all() serializer_class = serializers.ProjectQuestionAnswerChoiceSerializer filter_backends = ( filters.QueryParameterValidationFilter, django_filters.DjangoFilterBackend, ) filterset_fields = { "id": … -
Filter objects that have a foreign key from another object - Django
I want to filter Employee, only those that have a ForeignKey, how to do it? My solution does not returned any results. Models.py class Employee(models.Model): name = models.CharField(max_length=200) class ExperienceCategory(models.Model): name = models.CharField(max_length=100, unique=True) class Experience(models.Model): user = models.ForeignKey(Employee, on_delete=models.CASCADE) category = models.ForeignKey(ExperienceCategory, on_delete=models.CASCADE) Views.py experience_category = *ExperienceCategory object (1)* #solution - final query employee_query = Employee.objects.filter(experience__category = experience_category) How to get employees who have a foreign key from Experience? -
Django runserver hangs on Apple M1 macbook
I have django 3.2.12 application. It is running in docker with image python:3.9.12-slim-buster. When I'm accessing my app through web browser, it often hangs for some time (request pretty always takes exactly 5s - weird). This happens on chrome, firefox, safari. But only on Macbook with M1 CPU, on intel works fine. This problem only exist on runserver, it doesn't exist on gunicorn. The only solution, which I found, is to add '--nothreading' but this is not really a solution. Do you maybe know what can be an issue here? -
Git Bash automaticaly quits the server
When I use a command py manage.py runserverin Git Bash i get: "Watching for file changes with StatReloader" but nothing happens. If i press "Ctrl+C" i get URL and the server instantly stops https://i.stack.imgur.com/J7LWr.png If I don't press "Ctrl+C" but print http://localhost:8000/ in browser myself - URL works P.S. In Cmd everything works properly -
Does Django support all types of website templates(downloaded from web) that have different styles.?
enter image description here When i used a template to my project the styles dont appear correctly. What am i doing wrong? -
Django admin: Editing records with unique fields fails
Python 3.9, Django 3.2, Database is PostgreSQL hosted on ElephantSQL. I have a model, with a slug-field which I have set to unique: class website_category(models.Model): fld1 = models.CharField(primary_key=True, max_length=8) fld2 = models.TextField() fld3 = models.SlugField(unique=True, db_index=True, max_length=100) I can create new records for this model without any issue. However, when I try to edit an already existing record via the Django admin interface (e.g., change the text field - fld2), Django throws this error: website_category with this fld3 already exists I can delete the said record and re-enter the modified one without any issues. I can edit the record if I change the slug field but not otherwise. My guess is this is happening due to the "unique=True" set in the slug field (fld3). However, I do want the slugs to be unique. Is this an expected behaviour of Django or can I do something to make it possible for me to edit the records directly without having to delete and recreate them? -
Wagtail {{document.url}} is returning a 404 for user-uploaded files, in production
I've inherited a Wagtail CMS project but have been unable to solve an issue relating to document uploads. Having uploaded a file through the CMS, it arrives in the documents directory /var/www/example.com/wagtail/media/documents/test_pdf.pdf which maps to the /usr/src/app/media/documents/test_pdf.pdf directory inside the docker container. In the front end (and within the Wagtail dashboard) the document.url resolves to https://example.com/documents/9/test_pdf.pdf/ which returns a 404. Obviously the model number segment is missing from the file path above, but I read on a forum that In Wagtail, documents are always served through a Django view (wagtail.wagtaildocs.views.serve.serve) so that we can perform additional processing on document downloads so perhaps this, in itself, is not an issue. There are a couple of lines in urls.py file which look correct: urlpatterns = [ url(r'^django-admin/', admin.site.urls), url(r'^admin/', include(wagtailadmin_urls)), url(r'^documents/', include(wagtaildocs_urls)), url(r'^search/$', search_views.search, name='search'), url(r'^sitemap\.xml$', sitemap), url(r'', include(wagtail_urls)), # url(r'^pages/', include(wagtail_urls)), ] if settings.DEBUG: ... urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and in base.py MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/ So, my hunch is one of either: Uploads being stored incorrectly, in a single folder rather than in subdirectories by model The routing to this “virtual” directory is broken, so it’s breaking at the "check permissions" stage (but I couldn't figure out … -
remove first and last quote from python list
I have a list list = ['1,2,3,4,5,6,7'] I want my list as under: desire output = [1,2,3,4,5,6,7] how to get this, i read other similar answer where strip method used. i had tried strip but strip method not work with list, it work with strings. 'list' object has no attribute 'strip' -
Upload files and send to API with Javascript
I want to receive a file from the user in the frontend and send it to the API so it can be stored, alongside with some other data. However, in the backend (Django), I only receive the path for that file instead of the file itself and I'm sending the data with the "multipart/form-data" encoding type. HTML: <input [(ngModel)]="file" type="file" id="file" name="file" accept=".edf" required> TypeScript service: submitEEG(patientID: string, operatorID: string, file: File) : Observable<EEG> { let formData = new FormData(); formData.append("file", file); formData.append('patientID', patientID); formData.append('operatorID', operatorID); console.log(patientID); console.log(operatorID); console.log(file); return this.http.post<any>(this.BASE_URL + 'createEEG', formData); Data received in the REST API: Can someone help me? Thanks! -
Which Django generated files can be safely deleted
Simple question but I can't find exact answers on the web about it but by cleaning my Django app before it is ready I was thinking about which Django unused files I could safely delete to clean my app paths. The one I'm not using and wondering about : admin.py apps.py test.py models.py Thank you in advance for your help ! -
AWS image upload with Python/Django is not working
I am a beginner using Python/Django. few months ago I deployed an app that has an image upload feature which is connected with AWS S3 buckets. when I run the server locally on my machine, the app works fine. However I deployed the app to Heroku and the image upload stopped working, no errors in the console, and the image itself is not even uploaded to the AWS bucket. This is my views for uploading the images: def add_photo(request, team_id): photo_file = request.FILES.get('photo-file', None) if photo_file: s3 = boto3.client('s3') key = uuid.uuid4().hex[:6] + photo_file.name[photo_file.name.rfind('.'):] try: s3.upload_fileobj(photo_file, BUCKET, key) url = f"{S3_BASE_URL}{BUCKET}/{key}" photo = Photo(url=url, team_id = team_id) photo.save() except Exception as e : print('An error occured uploading files to s3') print(e) return redirect('teams_detail', team_id = team_id) this is the template for upload : {% for photo in team.photo_set.all %} <img src="{{photo.url}}" alt="{{photo.url}}" class="responsive-img card-panel"> {% empty %} <div class="card-panel teal-text center-align">No Photos Uploaded</div> {% endfor %} <form class="card-panel" action="{% url 'add_photo' team.id %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="photo-file"> <br> <br> <input type="submit" class="btn" value="Upload Photo"> </form> Like I said this is an app that I created a few months ago. so appreciate if you can point out … -
Django: how to retrive latest news from hackernews api using django
i am trying to retrieve the lastest news from hackernews api, everthing seems to be working fine and when i print the status code, i get Status Code:200 meaning it all working fine, but then i don't get any data. the code below is going to get some data using the api and save it to a model that i already created, and then i also have a view that display the news in my templates. So how do i get the news from the api? import dateutil.parser import datetime import requests from celery import shared_task from django.template.defaultfilters import slugify from .models import LatestStory, Comment BASE_API_URL = "https://hacker-news.firebaseio.com/v0" def get_item(id): item = requests.get(f"{BASE_API_URL}/item/{id}.json") return item.json() @shared_task def get_and_store_story_comments(unique_api_story_id, story_id): single_story = get_item(unique_api_story_id) story = LatestStory.objects.get(id=story_id, unique_api_story_id=unique_api_story_id) for kid in single_story.get("kids", []): comment_response = get_item(kid) comment, _ = Comment.objects.get_or_create(unique_comment_api_id=kid, id=story.id) comment.story = story comment.story_type = comment_response.get("type", "") comment.author = comment_response.get("by", "") comment.time = dateutil.parser.parse( datetime.datetime.fromtimestamp(comment_response.get("time", 0)).strftime("%Y-%m-%d %H:%M:%S") ) comment.text = comment_response.get("text", "") comment.comment_url = comment_response.get("url", "") comment.score = comment_response.get("score", 0) comment.save() def get_max_item_id(): max_item_id = requests.get(f"{BASE_API_URL}/maxitem.json") return max_item_id.json() @shared_task def store_latest_stories(): max_item_id = get_max_item_id() for sid in reversed(range(max_item_id)): story_response = get_item(sid) story, _ = LatestStory.objects.get_or_create( unique_api_story_id=sid, title=story_response.get( "title", f"No title for … -
How to use count() and sum() in serializer?
I want to calculate the average rating on sum_of_rating/number_of_rating. class SearchWorkingProgessionals(APIView): def post(self,request,format=None): tags = request.data.get('tag_arr') city_name = request.data.get('city_name') tags_list = tags.split(',') ws = WorkSamplesModel.objects.filter(business_account__serviceareasmodel__city_name=city_name, business_account__professiontagsmodel__tag_name__in=tags_list, is_business_card_image=True).distinct() serializer = SearchWorkingProgessionalsSerializer(ws,many=True) resp = {'resp':serializer.data} return Response(resp) class FeedbackModel(models.Model): feedback_text = models.CharField(max_length=20) rating = models.IntegerField() business_account = models.ForeignKey(BusinessAccountModel,on_delete=models.CASCADE) class Meta: db_table = 'feedback' This is my current serializer class SearchWorkingProgessionalsSerializer(serializers.Serializer): business_account_id = serializers.IntegerField() first_name = serializers.CharField(source='business_account.user.first_name') last_name = serializers.CharField(source='business_account.user.last_name') profile_pic = serializers.ImageField(source='business_account.user.profile_pic') business_title = serializers.CharField(source='business_account.business_title') business_description = serializers.CharField(source='business_account.business_description') status = serializers.CharField(source='business_account.status') note = serializers.CharField(source='business_account.note') work_sample_image = serializers.ImageField() work_sample_description = serializers.CharField(max_length=1000) How to calculate average rating using this serializer? -
Table with total summary per year-month Django
I have an expense accounting application, I need to make a table of expenses by year and month, I have a query like: queryset.all().values_list('date__year', 'date__month').annotate(Sum('amount')).order_by('date__year', 'date__month') I got a queryset with amounts by month, how do I get the amounts for each year nicely? I did, but I got a monster of 15 lines: def get_per_year_month_summary(queryset) -> OrderedDict: years_months = OrderedDict() years = sorted(set(map(lambda x: x['year'], queryset .annotate(year=ExtractYear('date')).values('year')))) for year in years: months = sorted(set(map(lambda x: x['month'], queryset .filter(date__year=year) .annotate(month=ExtractMonth('date')) .values('month')))) total_year = queryset.filter(date__year=year).aggregate(Sum('amount'))['amount__sum'] years_months[str(year)] = total_year for month in months: sum_month = \ queryset.filter(date__year=year, date__month=month).aggregate(Sum('amount'))['amount__sum'] years_months[f'{year}-{month}'] = sum_month return years_months Model: class Expense(models.Model): category = models.ForeignKey(Category, models.PROTECT, null=True, blank=True) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) -
How to call Python-django function(scrap the data from website) within the html?
I saved the links of one website in the database and searched them one by one from the Html search box, it gives me the scraped CSV file. When I searched for another website it throws an error. So I created another function with scraping code and return the value on a different Html page. Django only reads the first function. I'm stuck here. My scraping code fetches the details properly in another python file.Here are views.py,views.py,Here is urls.py,Here is index.html where search the link,Here is amazon.html should be downloaded the scraped data. -
Django - Filter a queryset by a property value
I would like to filter a queryset by the field id which is in an array of objects. I already have the id to compare this field to ie request.user.id which I get from the authenticated user. Lets assume that the logged in user has an id = 290 Thus; request.user.id = 290 Below is the structure of the Queryset [ { "id":"93b9f61a-a5c9-4c26-99a4-22f5447bdd3f", "approval_status":"not approved", "assignee":[ { "id":289, "username":"zverifier" } ], "sector":"Electricity" }, { "id":"270387f6-3c5c-4289-8baa-08441f318ec1", "approval_status":"approved", "assignee":[ { "id":289, "username":"zverifier" }, { "id":290, "username":"yverifier" } ], "sector":"Electricity" } ] I have tried using this; queryset = queryset.filter(assignee=request.user.id) but it only stops at the assignee and cant proceed to the id field within assignee.At the end of the day, I would like the Authenticated user to only see objects in which he is an assignee. -
Optimizing handling multiple requests in Django
I'm trying to build a simple REST API with Django. It works really good when dealing with a low rate of requests, but when I mock 100+ requests simultaneously the responses time goes from 0.3 seconds to around 3-4 seconds. I've check the runtime of my view and it no more than 0.1 seconds no matter what, which make me thinking that the problem is in the response sending itself. Any ideas how to optimize it? The model + view that I'm using: class Permutation(models.Model): id = models.AutoField(primary_key=True) hash_code = models.TextField(null=False, unique=True) all_permutations = models.TextField(null=False) @api_view(['GET']) def similarWords(request): word = request.GET.get('word', None) start_time = datetime.now() if not word or not word.isalpha(): updateLogs(start_time) print('invalid word') return HttpResponse(status=400) perm = Permutation.objects.filter(hash_code=getHashCode(word)) if not perm: updateLogs(start_time) return HttpResponse(json.dumps({'similar': []}), content_type="application/json", status=200) else: perm = perm.first() permutations_array = perm.all_permutations.split(' ') if word in permutations_array: permutations_array.remove(word) data = {'similar': permutations_array} updateLogs(start_time) return HttpResponse(json.dumps(data), content_type="application/json", status=200) -
Distinct values on annotated field using ArrayAgg
I'm trying to annotate to queryset field containing list of user account uuids interested and not interested in participation in some kind of event. This project uses Django 1.11 and PostgreSQL, so i wanted to annotate this list using ArrayAgg. Sadly this version of Django does not support distinct kwarg on ArrayAgg so list I'm getting back contains duplicated elements. Things that I have tried: Using properties on model - this works well and results are good, but instead of 2 queries in 10ms it does ~300 queries in 200ms. It's on development DB so it will be much more noticable on production. Implementing my own ArrayAgg and Aggregate using code from Django 2.0 repo and it works well, I'm getting desired 2 queries, but is there better way so I can evade such "hacky" solution? I can't update Django to version 2.0 Code example: It's version with displayed duplicates models.py import uuid as uuid from django.db import models class Account(models.Model): uuid = models.UUIDField(default=uuid.uuid4) class MyUser(models.Model): account = models.OneToOneField(Account, on_delete=models.CASCADE) class InterestStatus(models.Model): name = models.CharField(max_length=100) interested = models.ManyToManyField(MyUser, related_name='interested') not_interested = models.ManyToManyField(MyUser, related_name='not_interested') @property def interested_users_uids(self): ids = [] for user in self.interested.all(): ids.append(user.account.uuid) return ids @property def not_interested_users_uids(self): ids … -
Django - crispy forms not rendering in the browser
I'm new to django and I'm working on a blog project, but the browser does not render my form on the profile page. Specifically the form to update an profile image. Here's my code: forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField() # A class to specify the model the form is going to interact with class Meta: model = User # Fields wanted in the form and in what order: fields = ['username', 'email', 'password1', 'password2'] # A model form is a form that allows the creation of a form that will work with a specific database model class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] views.py def register(request): # If it gets a POST request then it instantiates a user creation form with that POST data if request.method == 'POST': # Create a form that has the request POST data: form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, 'Your account was created. You are now able to log in') return redirect('login') # With any other request it creates an empty user creation form else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) … -
Adding a model object and removing one from a different class via single request in Django Admin
It is my first time writing a django application and while I dive in the documentation I was hoping for more experienced suggestions. The models I'm working with are the following: Django Models The intended functionality is as follows - An admin populates the fields and if the 'featured' field is enabled, the 'replace with' field is shown. The 'replace with' field has the objects of the other class 'NewsFeatured'. When submitted: the object from the 'replace with' field is removed from 'NewsFeatured' the object from class 'News' is added to both 'News' and 'NewsFeatured' What I thought of is making a preflight request with javascript when submitting the form with a custom handler in my views and the Django ORM, but I was hoping I can do it from the same request - POST /admin/app/news/add I am trying to figure out the part of code in Django/Core that handles models in the admin site but any help would be appreciated! -
Django - ModelForm has no model class specified
Django is giving me the following error: ModelForm has no model class specified Traceback Traceback (most recent call last): File "C:\Users\Laila\.virtualenvs\BlogProject-71CaIFug\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Laila\.virtualenvs\BlogProject-71CaIFug\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Laila\.virtualenvs\BlogProject-71CaIFug\lib\site-packages\django\contrib\auth\decorators.py", line 23, in _wrapped_view return view_func(request, *args, **kwargs) File "D:\Programming\Python\Projects\Django\BlogProject\django_project\users\views.py", line 35, in profile userUpdateForm = UserUpdateForm() File "C:\Users\Laila\.virtualenvs\BlogProject-71CaIFug\lib\site-packages\django\forms\models.py", line 356, in __init__ raise ValueError("ModelForm has no model class specified.") Exception Type: ValueError at /profile/ Exception Value: ModelForm has no model class specified. Here's my code: forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() # A class to specify the model the form is going to interact with class Meta: model = User # Fields wanted in the form and in what order: fields = ['username', 'email', 'password1', 'password2'] # A model form is a form that allows the creation of a form that will work with a specific database model class UserUpdateForm(forms.ModelForm): model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] views.py from django.shortcuts import render, redirect from django.contrib import messages from .forms import UserRegisterForm, UserUpdateForm, … -
Django Set foreign key field in model from the url parameter
I have a foreign key field in my model which should be set from the url params when the model is saved.I need to set the field automaticatically from the registration-id models.py class Mymodel(BaseModel): name = models.CharField() created_by = models.ForeignKey( 'User', related_name='', null=True, blank=True, on_delete=models.SET_NULL ) last_edited = models.DateField(auto_now=True) registration = models.ForeignKey( SomeModel, related_name='', null=True, blank=True, on_delete=models.SET_NULL ) views.py class MyCreateView(LoginRequiredMixin, CreateView, CustomPermissionMixin): form_class = '' pk_url_kwarg = '' template_name = 'c.html' def form_valid(self, form): form.instance.created_by = self.request.user.person return super().form_valid(form) def get_success_url(self): return reverse('') forms.py class MyModelForm(forms.ModelForm): class Meta: model = Mymodel fields = ('name',) urls.py '<int:registration_id>/employee/create/' -
Can’t install Pillow to deploy a Django web app to AWS beanstalk
I am trying to deploy A django app to beanstalk and I get some errors related to python and requirements.txt and I can't figure out what to do, Any help is appreciated. Here are the errors I get: (the logs are in pastebin bellow) ERROR Instance: i-0e7826c4558b1d21a] Command failed on instance. Return code: 1 Output: (TRUNCATED)...) File "/usr/lib64/python2.7/subprocess.py", line 190, in check_call raise CalledProcessError(retcode, cmd) CalledProcessError: Command '/opt/python/run/venv/bin/pip install -r /opt/python/ondeck/app/requirements.txt' returned non-zero exit status 1. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/03deploy.py failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. 2022-04-28 15:13:52 UTC+0000 ERROR Your requirements.txt is invalid. Snapshot your logs for details. logs: https://pastebin.com/g1uZLqur here is my requirements.txt Django==2.2.6 django-environ==0.4.5 pytz==2019.3 sqlparse==0.3.0 django-paypal==1.0.0 https://github.com/darklow/django-suit/tarball/v2 git+https://github.com/nn3un/reportlab-mirror#egg=reportlab boto3==1.4.4 django-storages==1.8 psycopg2 django-guardian bokeh==1.4.0 django-ses==2.0.0 mock -
fetching image using django-graphql-vue3 apollo
Is it possible to query image or upload any file on local storage using django backned and vue3 apollo4 through graphql? Does anyone have any reference or tutorial that might help me understand this? Please provide me the link if you have one. Thanks a lot. -
django returns MultiValueDictKeyError at / 'q'
django returns MultiValueDictKeyError at / 'q' in my dashboard template when I'm trying to add search functionality into my app. I want when a user type something on the search input to return the value that user searched for. but i endup getting an error when i try to do it myself. MultiValueDictKeyError at / 'q' def dashboard(request): photos = Photo.objects.all() query = request.GET['q'] card_list = Photo.objects.filter(category__contains=query) context = {'photos': photos, 'card_list':card_list} return render(request, 'dashboard.html', context) <div class="container"> <div class="row justify-content-center"> <form action="" method="GET"> <input type="text" name="q" class="form-control"> <br> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> <br> <div class="container"> <div class="row justify-content-center"> {% for photo in photos reversed %} <div class="col-md-4"> <div class="card my-2"> <img class="image-thumbail" src="{{photo.image.url}}" alt="Card image cap"> <div class="card-body"> <h2 style="color: yellowgreen; font-family: Arial, Helvetica, sans-serif;"> {{photo.user.username.upper}} </h2> <br> <h3>{{photo.category}}</h3> <h4>{{photo.price}}</h4> </div> <a href="{% url 'Photo-view' photo.id %}" class="btn btn-warning btn- sm m-1">Buy Now</a> </div> </div> {% empty %} <h3>No Files...</h3> {% endfor %} </div> </div>