Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Editing a Post - Django and Javascript Question
I am new to Django and Javascript. I would like to create an edit section on a site, where people can edit a post that already exists. Similar to Facebook or Twitter. When I click 'edit' on my post, in the console I am getting: network.js:28 POST http://127.0.0.1:8000/edit_post/ 404 (Not Found) I've tried many things but cannot get it to work. Any help is appreciated. I think the issue might have to do with the use of 'post' and 'text.' 'text' is in my model, used to signify the text of the actual post. views.py: @login_required @csrf_exempt def edit_post(request): if request.method == "POST": post_id = request.POST.get('id') new_post = request.POST.get('text') try: post = Post.objects.get(id=post_id) if post.user == request.user: post.text = new_post.strip() post.save() return JsonResponse({}, status=201) except: return JsonResponse({}, status=404) return JsonResponse({}, status=400) models.py class User(AbstractUser): pass class Post(models.Model): text = models.TextField(max_length=500, blank=True, null=True) username = models.ForeignKey('User', on_delete=models.CASCADE, related_name='author', null=True, blank=True) timestamp = models.DateTimeField(auto_now_add=True) like = models.ManyToManyField( User, blank=True, related_name="liked_user") def __str__(self): return self.user.username Javascript file: edit = document.querySelectorAll(".edit"); text_area = document.querySelectorAll(".textarea"); edit.forEach((element) => { element.addEventListener("click", () => { edit_handeler(element); }); }); text_area.forEach((element) => { element.addEventListener("keyup", (e) => { if (e.keyCode == 13 && e.shiftKey) return; if (e.keyCode === 13) edit_handeler(element); }); … -
Using Two Different Models In Views to Return a Newly Created List, Not Already Called Querylist, With a For Loop
I am trying to create the following view: class FeedAPI(ObjectMultipleModelAPIView): #lookup_url_kwarg = 'id' def get_querylist(self, *args, **kwargs): id = self.kwargs['id'] props = Profile.objects.filter(id=id) followers = Profile.filter(followers.includes(props)) querylist = [ {'queryset': Profile.objects.filter(followers), 'serializer_class': ProfileSerializer}, {'queryset': Post.objects.all(), 'serializer_class': PostSerializer}, ] feedPosts= [] for x in followers: feedPosts = Posts.objects.filter(Source_id=Post.sourceID) return Response(props, feedPosts, status=status.HTTP_200_OK) But I get the error type object 'Profile' has no attribute 'filter' which according to stack overflow, comes because I am not returning a querylist in my def get_query list. So, I would like to know how I can just return the Post IDs that have the same sourceIDs associated with the followers of a profile. My models are Source, Profile, and Post. Profile and Post have sourceID ForeignKeys. Profile model* class Profile(models.Model): user = AutoOneToOneField(User, default=True, on_delete=models.CASCADE) sourceID = models.ForeignKey('Source', on_delete=models.CASCADE, related_name='+', blank=True, null=True) followers = models.ForeignKey( 'Source', on_delete=models.CASCADE, related_name='+', default='', blank=True, null=True) following = models.ForeignKey('Source', on_delete=models.CASCADE, related_name='+', default='', blank=True, null=True)``` ***Post model*** class Post(models.Model): sourceID = models.ForeignKey('Source', blank=True, on_delete=models.CASCADE, related_name='+', null=True) image = models.ImageField( "Post Picture", upload_to='post_pics', blank=True, null=True) title = models.CharField(max_length=50)``` Source model class Source(models.Model): profile = models.ForeignKey('Profile', on_delete=models.CASCADE, null=True, blank=True, related_name='+') def __str__(self): return str(self.id) -
AttributeError Exception Value: 'IntegerField' object has no attribute 'max_length'
I did not put any max_length restrictions on the IntegerField hence I am not sure what is the issue. The code below is in models.py. Please tell me what else do i need to provide to give a better understanding to this issue. Django version: Django==3.2 models.py from django.db import models class Rawdata(models.Model): id = models.IntegerField(db_column='id', primary_key = True) name = models.TextField(blank=True, null=True) node = models.TextField(blank=True, null=True) metal_stack = models.TextField(blank=True, null=True) thickness = models.DecimalField(max_digits=4, decimal_places=2,blank=True, null=True) mstk_id = models.IntegerField(db_column='MStk_id',blank=True, null=True) # Field name made lowercase. restrict = models.TextField(db_column='restrict', blank=True, null=True) # Field name made lowercase. class Meta: db_table = 'rawdata' class Technology(models.Model): id = models.IntegerField(db_column='id', primary_key = True) name = models.CharField(unique=True, max_length=45, blank=True, null=True) node = models.CharField(max_length=45, blank=True, null=True) def __str__(self): return self.name class Meta: db_table = 'technology' unique_together = (('name','node'),) class Metalstack(models.Model): id = models.IntegerField(db_column='id', primary_key = True) techname = models.ForeignKey('Technology', to_field = 'name', on_delete = models.CASCADE, db_column ="techname",blank=True, null=True) stackname = models.CharField(max_length=45, blank=True, null=True, db_column ="stackname") mstk_id = models.IntegerField(blank=True, null=True, db_column ="mstk_id") restrict = models.CharField(max_length=45, blank=True, null=True) def __str__(self): return self.stackname class Meta: db_table = 'metalstack' unique_together = (('techname', 'stackname', 'mstk_id'),) class Thickness(models.Model): id = models.IntegerField(db_column='id', primary_key = True) stack_id = models.ForeignKey(Metalstack, to_field = 'id', on_delete = models.CASCADE, … -
CORS not working in Django but settings seem correct
I am trying to make a POST call to Django from a React Native Web front end on different subdomains. I thought I had configured CORS correctly, but that does not seem to be the case. Here's what my Django settings.py looks like: CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = ['*'] CORS_ALLOWED_ORIGINS = ['https://api.example.com', 'https://example.com', 'https://www.example.com' ] CSRF_TRUSTED_ORIGINS = [ 'https://api.example.com', 'https://example.com', 'https://www.example.com' ] ALLOWED_HOSTS = ["0.0.0.0", "api.example.com", "example.com"] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', ] INSTALLED_APPS = [ ... 'corsheaders', ... ] What exactly am I doing wrong here? The error I'm getting is this: Access to XMLHttpRequest at 'https://api.example.com/api/v1/pagescreate/' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. And this is my Django view: class PageCreateView(generics.CreateAPIView): queryset = Page.objects.all() serializer_class = PageSerializer What could be causing this? Am I missing some setting in React? I'm using axios to make the calls, with the only header being "Content-Type": "application/json" -
How to return serializer to bulk create
I have a model which saves some files to db. When I upload nested zip file (zip files inside main zip) I need to create an object for every file inside and return created objects in serializer. models.py class CampaignManagerCreativeAsset(models.Model): asset_file = models.FileField( validators=[validate_file_extension], storage=AssetsMediaStorage() ) mimetype = models.CharField(max_length=50, null=True) helpers.py def _check_for_nested_zip(zip_file): all_zip = list() for file in zip_file.namelist(): if file.lower().endswith('.zip'): all_zip.append(True) else: all_zip.append(False) return all_zip def process_zip_file(file_object): with ZipFile(file_object, 'r') as zip_file: all_zip = _check_for_nested_zip(zip_file) if all(all_zip): files_to_create = list() files_content = {name: zip_file.read(name) for name in zip_file.namelist()} for filename, content in files_content.items(): file = SimpleUploadedFile.from_dict( { 'content': content, 'filename': filename, 'content-type': 'application/zip', } ) files_to_create.append(file) return files_to_create return file_object views.py class CreativeAssetViewSet(viewsets.ModelViewSet): serializer_class = serializers.CreativeAssetSerializer filter_fields = '__all__' def get_queryset(self): return models.CampaignManagerCreativeAsset.objects.all() serializers.py class CreativeAssetSerializer(serializers.ModelSerializer): class Meta: model = models.CampaignManagerCreativeAsset fields = ( 'id', 'external_creative_asset_id', 'asset_file', 'settings', 'mimetype', ) read_only_fields = ('id', 'external_creative_asset_id', 'mimetype') def create(self, validated_data): asset_file = validated_data.get('asset_file') settings = validated_data.get('settings') mimetype = helpers.get_mimetypes_type(asset_file.name) instances = list() if mimetype == 'application/zip': files_to_create = helpers.process_zip_file(asset_file) if not isinstance(files_to_create, list): instances.append(models.CampaignManagerCreativeAsset(**validated_data)) else: for file in files_to_create: instances.append( models.CampaignManagerCreativeAsset( asset_file=file, settings=settings ) ) return models.CampaignManagerCreativeAsset.objects.bulk_create(instances) But I am getting error Got AttributeError when attempting to get a value … -
How to put implement chart.js into an existing page django
I am making this website that has this function that shows total hours worked for the employee. I want to make so that when it shows the total hours worked, it will also show the hours worked for each day in that month. I managed to do the chart for that but the chart will show on another page so how do I show the chart and the total hours worked on the same page? code: def checkTotalHours(response): empName = employeeName.objects.all() if response.method == "POST": if 'checkName' in response.POST: n = response.POST.get("check") emp = employeeName.objects.get(employee=n) time = emp.total_Hours_Worked messages.info(response, time + ' hours') f = Name.objects.filter(name=emp) allDate = [] cIn = [] today = datetime.today() datem = today.month for date in f: allDate.append(date.date) totalTime = (datetime.combine(date.date, date.timeOut)- datetime.combine(date.date, date.timeIn)).seconds/3600 cIn.append(totalTime) hours = int(totalTime) minutes = (totalTime*60) % 60 seconds = (totalTime*3600) % 60 time = "%d:%02d:%02d" % (hours, minutes, seconds) #cIn.append(time) global cInUpdated global allDateUpdated cInUpdated = [] allDateUpdated = [] for item in range(len(allDate)): if allDate[item].month == datem: cInUpdated.append(cIn[item]) allDateUpdated.append(allDate[item]) print("Here:: ", allDate[item].month," ", cIn[item] ) else: continue for item in range(len(cInUpdated)): print("Work: ", allDateUpdated[item], " ",cInUpdated[item]) return redirect('/totalHours') else: form = CreateNewList() return render(response, "main/checkTotalHours.html", {"empName":empName}) HTML: {% … -
Django, how to update my following list using fetch and PUT in JavaScript?
I have a method in views.py that adds user to the following list, I'm trying to make it work whenever I click on the button "follow" that I have added in JavaScript How do I make my Follow button in JavaScript go to my views.py method onclick ? views.py method. def follow(request, profile_to_follow): try: user_to_follow = User.objects.get(username=profile_to_follow) user_to_following = Profile.objects.get(user=request.user.id) except User.DoesNotExist: return JsonResponse({"error": "Profile not found."}, status=404) if request.method == "PUT": user_to_following.following.add(user_to_follow) return HttpResponse(status=204) urls.py # API Routes path("posts", views.compose_post, name="compose_post"), path("posts/all_posts", views.show_posts, name="show_posts"), path("posts/<int:post_id>", views.post, name="post"), path("profile/<str:profile>", views.display_profile, name="profile"), path("<str:profile_posts>/posts", views.display_profile_posts, name="profile_posts"), path("follow/<str:user_to_follow>", views.follow, name="follow"), JavaScript function load_user_info(user_clicked_on){ document.querySelector('#page-view').style.display = 'none'; document.querySelector('#posts-view').style.display = 'none'; document.querySelector('#show-posts').style.display = 'none'; document.querySelector('#load-profile').style.display = 'block'; fetch(`/profile/${user_clicked_on}`) .then(response => response.json()) .then(profile => { const profile_element = document.createElement('div'); const followers = document.createElement('div'); const following = document.createElement('div'); const follow_button = document.createElement('button'); follow_button.innerHTML += "Follow"; followers.innerHTML = 'Followers: ' + profile.followers; following.innerHTML = 'Following: ' + profile.following; profile_element.appendChild(followers); profile_element.appendChild(following); profile_element.appendChild(follow_button); profile_element.classList.add('profile_element'); follow_button.addEventListener("click", () => { follow_user(user_clicked_on) }); document.querySelector('#user-profile').appendChild(profile_element); }); document.querySelector('#user-profile').innerHTML = `<h3>${user_clicked_on.charAt(0).toUpperCase() + user_clicked_on.slice(1)} Profile</h3>`; } function follow_user(user_to_follow){ // to make this function work with the one in views.py fetch(`/profile/${user_to_follow}`, { method: 'PUT', }) } -
List and Retrieve actions generating additional CRUD actions (from ModelViewSet's get_permissions()?)
When I do a simple GET to my model's list or detail view, it actually appears to be running a whole bunch of additional and unasked-for actions under ModelViewSet's get_permissions(). So when I add print(self.action) under get_permissions() I get the following: Accessing model's list view (i.e. /authors/): list create create None Accessing model's detail view (i.e. /authors/1): retrieve retrieve update partial_update update destroy None None Why on earth is this happening? Shouldn't it simply print "list" for my list view and "retrieve" for my detail view? views.py class AuthorViewSet(viewsets.ModelViewSet): queryset = Author.objects.all() lookup_field = "pk" serializer_class = AuthorSerializer def get_permissions(self): print(self.action) # Print self.action code here if self.action == "create": permission_classes = [IsAuthenticated] elif self.action == "list" or self.action == "retrieve": permission_classes = [AllowAny] elif ( self.action == "update" or self.action == "partial_update" or self.action == "destroy" ): permission_classes = [IsAdminUser] # I have to include this final else statement or I get this error: # "UnboundLocalError: local variable 'permission_classes' referenced before assignment" # Probably because there is a self.action == "None" attempt? else: permission_classes = [AllowAny] return [permission() for permission in permission_classes] models.py class Author(models.Model): first_name = models.CharField(max_length=255, blank=True) last_name = models.CharField(max_length=255) serializers.py class AuthorSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="library:author-detail") class … -
Django None parameter function issue
When I input none value or other values that do not match with the patientName and patientNRIC in the database(sqlite), print(patient_data) shows Response 200, then there will be error in converting the patient_data into json bcs the patient_data actually contains no data, and is not None. How should I do so that I can make sure that the function can take it None values at the same time is able to validate/make sure patient_data contains information then return true or return json otherwise return false. Below is the fun with django url. Thank you for your help. def by_nric_name(patientsNRIC=(None,''), patientsName=(None,'')): params = {'patientName': patientsName, 'patientNRIC': patientsNRIC} django_url = "http://85c867e79dc5.ngrok.io/bynricandname/" patient_data = requests.get(django_url, params=params) print(patient_data) patient_data = patient_data.json() return patient_data -
How to fix Django server 503 error when upload a file?
I tried to upload a file by using django-rest-framework. This is my code what I tried. videofile = request.FILES['videoData'] fs = FileSystemStorage() filename = fs.save(videofile.name, videofile) user = request.user File.objects.create( user = user, title = request.data['videotitle'], url = filename, categorys = request.data['categories'], preveimage = request.data['vidoePrevimg'], filetype = request.data['videoType'], filesize = request.data['videoSize'] ) status_code = status.HTTP_200_OK response = { 'success': 'true', 'status code': status_code, 'message': 'Video uploaded successfully', } It works fine in local and when I deploy it to heroku, most APIs works fine, except file upload. The server returns 503 error. Please help me. Sorry for my English. Thank you in advance -
Django form creation using crispy
I followed a youtube video on how to create a page where a user can make a new post for a blog or a Q&A website. I need to able to add a section where the user inputs their zip code in order to then filter the posts by each zip code (for the sake of my web application). How do you recommend I go about this? This is how my code looks as of now. enter image description here -
mysql file not found in $PATH error using Docker and Django?
I'm working on using Django and Docker with MariaDB on Mac OS X. I'm trying to grant privileges to Django to set up a test db. For this, I have a script that executes this code, sudo docker exec -it $container mysql -u root -p. When I do this after spinning up, instead of the prompt for the password for the database, I get this error message, OCI runtime exec failed: exec failed: container_linux.go:370: starting container process caused: exec: "mysql": executable file not found in $PATH: unknown On an Ubuntu machine, I can delete the data folder for the database and spin up, spin down, and run the command without the error, but on my Mac, which is my primary machine that I'd like to use, this fix doesn't work. Any ideas? I've had a peer pull code and try it on their Mac and it does the same thing to them! Docker is magic to me. -
chartit causes 'django.utils' failure
Hi guys I have Installed Chartit, added it to my INSTALLED_APPs in setting.py : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'crispy_forms', 'chartit', ] I have a model as follows in my models.py : class DummyData(models.Model): site = models.CharField(max_length=40, blank=True) turn_over = models.CharField(max_length=40, blank=True) year = models.IntegerField(blank=True, null=True) This function in my views.py : def dashboard(request): dashboard = DataPool( series= [{'options': { 'source': DummyData.objects.all()}, 'terms': [{'site': 'site', 'turn_over': 'turn_over'}] }, ]) # Step 2: Create the Chart object cht = Chart( datasource=dashboard, series_options= [{'options': { 'type': 'column', 'stacking': False}, 'terms': { 'site': [ 'turn_over'] }}], chart_options= {'title': { 'text': 'dashboard Amounts Over Months'}, 'xAxis': { 'title': {'text': 'dashboard Total'}}, 'yAxis': { 'title': {'text': 'Month Number'}}, 'legend': { 'enabled': True}, 'credits': { 'enabled': True}},) # Step 3: Create a second chart object # Step 4: Send the chart object to the template. return render(request, 'dashboard.html', {'char_list': [cht]}) And finally rendering this html page : <!DOCTYPE html> <html lang="en"> <head> <!-- jQuery CDN --> <script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script> <!-- highcharts CDN --> <script src="https://code.highcharts.com/highcharts.src.js"></script> <script src="https://code.highcharts.com/highcharts-more.js"></script> <script src="https://code.highcharts.com/modules/exporting.js"></script> <script src="https://code.highcharts.com/modules/export-data.js"></script> <script src="https://code.highcharts.com/modules/heatmap.js"></script> <script src="https://code.highcharts.com/modules/treemap.js"></script> {% load chartit %} {{ chart_list|load_charts:"cht" }} </head> <body> <div id='cht' style="min-width: 310px; height: 400px; … -
Terminal is stuck on python manage.py makemigrations and runserver
I am using Pycharm for django development, after adding some models to the models.py the terminal is stuck at python manage.py makemigrations command, runserver doesn't work also. The terminal is freezing. It was working perfectly, it did not work after the modification in models.py, I tried to delete the migration files but it didn't work, restart the computer didn't help. Look at the pictures please. Any ideas? Thanks a lot makemigrations runserver -
python module installation error when deploying a Django application on heroku
I am deploying my django application on heroku. but when installing the modules from the requirement.txt file, it returns an error on the "Paydunya" module. I am deploying my django application on heroku. but when installing the modules from the requirement.txt file, it returns an error on the "Paydunya" module. I need your help to solve this problem. Thank you here is my requirement.txt file : six==1.15.0 dj-database-url==0.5.0 Django==3.2 django-advanced-filters==1.3.0 django-allauth==0.44.0 django-appconf==1.0.4 django-braces==1.14.0 django-compressor==2.4 django-crispy-forms==1.11.2 django-debug-toolbar==3.2 django-filter==2.4.0 django-heroku==0.3.1 django-markdown-deux==1.0.5 django-money==1.3.1 django-pagedown==2.2.0 django-rest-framework==0.1.0 django-tastypie==0.14.3 django-tinymce==3.3.0 django-videofield==0.1.1 django-widget-tweaks==1.4.8 djangorestframework==3.12.4 docutils==0.17 fpdf==1.7.2 future==0.18.2 gunicorn==20.1.0 html5lib==1.1 idna==2.10 joblib==1.0.1 Markdown==3.3.4 markdown2==2.4.0 Pillow==8.2.0 Pygments==2.8.1 PyJWT==2.0.1 pyparsing==2.4.7 PyPDF2==1.26.0 python-decouple==3.4 python-dotenv==0.17.0 requests==2.0.1 requests-mock==1.3.0 requests-oauthlib==1.3.0 rjsmin==1.1.0 simplejson==3.17.2 sqlparse==0.4.1 suit==2.0.2 urllib3==1.26.4 virtualenv==20.4.3 whitenoise==5.2.0 xhtml2pdf==0.2.5 paydunya==1.0.6 Here is the Heroku CLI : C:\Users\aba\Desktop\comsoc-ugb>git push heroku master Enumerating objects: 17, done. Counting objects: 100% (17/17), done. Delta compression using up to 4 threads Compressing objects: 100% (15/15), done. Writing objects: 100% (15/15), 1.33 KiB | 1.33 MiB/s, done. Total 15 (delta 10), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> No Python version was specified. Using … -
Django LogoutView redirect to previous page
I am using Django's auth.LogoutView class in my urls.py. I can redirect the user to a specific page using LogoutView.as_view(next_page='main:index') after logout. If I left out the next_page part, it redirects to a Django admin interface with a thank you message and a option to login again, which is the admin login page. I want to redirect the user to the page they were on before clicking the logout url on the navbar. -
How can I return a response from docker url in Django?
I'm trying to make a textbox area. In that textbox area user will going to write a sentence and then they will recieve a output about that text. Output is coming from a docker image. And I try to connect them locally by writing it's url. Here my views.py, urls.py and html file. views.py def sentiment(request): url = "http://localhost:5000/sentiment" #this is my local docker image url. input_text = request.GET.get('text') try: response = request.get(url+input_text).json() context = { 'text':text } return render(request,'blog/links/Link1.html',context) except: return redirect ("/duyguanalizi") urls.py from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns = [ path('', views.index, name='kaydol'), path('anasayfa/', views.home, name='anasayfa'), path('duyguanalizi/', views.link1, name='duyguanalizi'), path('duyguanalizi/sonuc', views.sentiment, name='da_sonuc'), path('anahtarkelime/', views.link2, name='anahtarkelime'), path('özetleme/', views.link3, name='özetleme'), path('advarlık/', views.link4, name='advarlık'), path('sorucevap/', views.link5, name='sorucevap'), path('konutanım/', views.link6, name='konutanım'), ] urlpatterns += staticfiles_urlpatterns() html <div class="side_container side_container--fit "> <div class = "item-1"> <form class="" action="{% url 'da_sonuc' %}" method="GET"> <label for="textarea"> <i class="fas fa-pencil-alt prefix"></i> Duygu Analizi </label> <h2>Kendi Metniniz ile Test Edin...</h2> <input class="input" id="textarea" value="{{text}}"> </input> <br> <button type="button" class="btn">Dene</button> </form> <label> Sonuç </label> <div class="outcome"> <p>{{text}}</p> </div> </div> -
REST API with image processing?
This may not be a great question but I am new to API's and REST API's. I understand what API's do, and have a general understanding of REST API's (GET, POST, SET, etc). What I'm confused about is in almost all examples I've seen, the REST API's are database related (query data, update data, insert new data, etc). So I was wondering, if I wanted to create an API where I can send an image, process it in the backend (in Python) and return some image and annotations, is this still considered a REST API, and are there any conventions/advice for this kind of thing? -
Django save image from url and connect with ImageField don't work
I want django automatically download and locally save image from image_url and "connect" it with image_file how Upload image from an URL with Django from django.core.files import File import os class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField( upload_to=user_directory_path, default='users/avatar.png') bio = models.TextField(max_length=5500, blank=True) fullName = models.CharField(max_length=221, blank=True, default=rand_slug(5) ) dr = models.BooleanField( default=False ) slug = models.SlugField(max_length=250, unique=True, blank=True, default=rand_slug(8)) facebook = models.URLField(max_length=222, blank=True) twitter = models.URLField(max_length=222, blank=True) image_file = models.ImageField(upload_to='images') image_url = models.URLField() def get_remote_image(self): if self.image_url and not self.image_file: result = urllib.urlretrieve(self.image_url) self.image_file.save( os.path.basename(self.image_url), File(open(result[0])) ) self.save() def __str__(self): return self.user.username -
Added a Non-Nullable Field in Django After Creating Entries That Didn't Have That Field; Operational Error, No Such Field
In my models, I added the class Source: class Source(models.Model): profile = models.ForeignKey('Profile', on_delete=models.CASCADE, null=True, default=False, blank=True, related_name='+') project= models.ForeignKey('Project', on_delete=models.CASCADE, null=True, default=False, blank=True, related_name='+') team = models.ForeignKey('Team', on_delete=models.CASCADE, null=True, default=False, blank=True, related_name='+') department = models.ForeignKey('Department', on_delete=models.CASCADE, default=False, blank=True, null=True, related_name='+') def __str__(self): return str(self.id) For testing purposes, I added a few entries for posts in the Django admin page, and then went back into my classes: Post, Profile, Department, Team, and Project, and added: sourceID = models.ForeignKey('Source', default='1', on_delete=models.CASCADE, related_name='+', null=False) for each class. My problem is that when I go in the Django admin page to alter the database (i.e. create a new post) I get the following error: Also, when I go to migrate my changes, I keep getting this warning: HINT: Configure the DEFAULT_AUTO_FIELD setting or the LeadsConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'. I would like to be able to create new entries in my database without the operational error. I've tried changing the null value = True, but this is counterintuitive and doesn't yield any change, surprisingly. I think the best way would be to delete the whole database, which I've tried to research and only found MYSql code solutions. … -
Django generic DeleteView auth
I want to create a post that only the author and the authorities can delete. class PostDeleteView(DeleteView): model = Posts template_name = 'deletepost.html' success_url = '/home' Currently all users can delete posts. -
why does Django Slice works on one page and not the other
This allows me to slice #models.py Class Home(models.Model): house_name = models.CharField(max_length=20, blank=False, null=True) location = models.CharField(max_length=20, blank=False, null=True) rooms = models.CharField(max_length=20, blank=False, null=True) def save(self, *args, **kwargs): self.slug = slugify(self.house_name) super(Home, self).save(*args, **kwargs) #views.py def homes(request): home_model = Home.objects.filter(admin_approval=True) return render(request, 'home/home.html', {'home_model': home_model}) #home.html <div class="container"> <div class="row row-cols-lg-4 row-cols-md-3 text-center text-light"> {% for home in home_model|slice:":10" %} <div class="row-inside-content"> <a href="{% url 'home_detail' home.slug %}"><img src="#"></a> <p><a href="#">{{ home.home_name|title }}</a></p> </div> {% endfor %} </div> Meanwhile if I was to use the same views, and same model and also try to render homes in another page like home/house.html, nothing gets render. I'm utterly confused as to why this is happening. -
Q Filter by alphabet
I attempting to create an alphabet filter in my project that will return all objects that begin with a specific letter. This is my current view class ArtistLetterView(ListView): model = Artist context_object_name = 'artist' template_name = "artist/alpha_list.html" def get_queryset(self): query = self.request.GET.get('q') artist = Artist.objects.filter( Q(stage_name__startswith=query) ) return artist This is my URL path('letter_search/', views.ArtistLetterView.as_view(), name='list_letter'), Currently if I manually enter a path like this http://127.0.0.1:8000/artist/letter_search/?q=D it works. How can I place this functionality into an href? Or am I completely doing this wrong? -
3 way many to many relationship in Django with two inline forms
I'm working on a personal project for educational reasons. I have 3 models (RatePlans, Seasons, RoomRates). Each RatePlan should have multiple Seasons and each Season should have multiple RoomRates. I want to be able to create a RatePlan in the admin panel and then with inlines to create multiple Seasons and also (if it's possible) multiple RoomRates in the same view. How the models should be structured (oneToMany, ManyToMany, do i need a 4th table or how i should do it)? Can i create all of the records in one way in the admin panel (for example to go to RatePlans and start populating the Seasons and the RoomRates at the same time)? Those are my models class RatePlan(models.Model): code = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50, unique=True) market_segment = models.ForeignKey(MarketSegment, on_delete=models.CASCADE) class Season(models.Model): code = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50, unique=True) date_from = models.DateField() date_to = models.DateField() class RoomRate(models.Model): code = models.CharField(max_length=50) room_type = models.ForeignKey(RoomType, on_delete=models.CASCADE) charge = models.DecimalField(max_digits=6, decimal_places=2) charge_method = models.ForeignKey(ChargeMethod, on_delete=models.CASCADE) Thanks in advance -
Programming Error in deploying Django website on Heroku
I am learning Django and wanted to deploy the app on Heroku. upon following the Heroku documentation on deploying the app to the platform. It is throwing errors. I have 2 apps in the project: blog (for writing the blogs) userAuthentication (user auth) Please help! ERROR on Heroku deployed app: ProgrammingError at / relation "blog_categories" does not exist LINE 1: ...categories"."name", "blog_categories"."name" FROM "blog_cate... ^ Request Method: GET Request URL: https://sciencecreed.herokuapp.com/ Django Version: 3.2 Exception Type: ProgrammingError Exception Value: relation "blog_categories" does not exist LINE 1: ...categories"."name", "blog_categories"."name" FROM "blog_cate... ^ Exception Location: /app/.heroku/python/lib/python3.9/site-packages/django/db/backends/utils.py, line 84, in _execute Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.4 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Thu, 29 Apr 2021 21:36:58 +0000 ERROR on executing "heroku logs" I believe all this will help in assisting.