Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
SKLearn Feature Selection: AttributeError: 'numpy.float64' object has no attribute '_get_tags'
An error is raised when the .fit() method is called after the RFE execution. What might caused the error? df = pd.read_csv(project.base_file, encoding='ISO-8859-1') X = df.drop(['colun1', 'column2'] , axis=1) y = df[target_column] X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.2, random_state = 0) sel = RFE(run_randomForest_classifier(X_train, X_test, y_train, y_test), n_features_to_select=15) ### THE NEXT LINE THROWS THE ERROR ### AttributeError: 'numpy.float64' object has no attribute '_get_tags' sel.fit(X_train, y_train) -
How to fix 'Manager' object has no attribute 'get_or_created'
I am trying to create a Like button for my Django Blog Project, I have followed a Tutorial step by step but currently facing an new error I haven't faced before: 'Manager' object has no attribute 'get_or_created' My Question is how to fix this error as it appears when I click on the Like button in the template? Here is the models.py class Post(models.Model): liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') ...................................... @property def num_likes(self): return self.liked.all().count() LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) date_liked = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.post) Here is the views: class PostListView(ListView): model = Post template_name = "blog/post_list.html" # <app>/<model>_<viewtype>.html ordering = ['-date_posted'] context_object_name = 'posts' paginate_by = 1 class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res def like_post(request): user=request.user if request.method=='POST': post_id=request.POST.get('post_id') post_obj= Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like,created=Like.objects.get_or_created(user=user,post_id=post_id)<------------- Error from here if not created: if like.value=='Like': like.value='Unlike' else: like.value='Like' like.save() return redirect('blog:post_list') Here is the template: <form action="{% url 'blog:like-post' %}" method="POST"> {% csrf_token %} <input type="hidden" name="post_id" value='{{post.id}}'> {% … -
Django additional data not saving
I'm having an issue with my Django web app where I ask for data in a form which is saving correctly but it isn't saving the additional data from views. I am trying to save the user data of the person who posted this and the event id but it's not saving that info for some reason. @login_required def newrider(request, Event_id): events = get_object_or_404(Event, pk=Event_id) riders = rider.objects.filter(event=Event_id) if request.method == 'GET': return render(request, 'web/newrider.html', {'form': AddRiderForm()}) else: if request.user.is_authenticated: item = rider.objects.filter(number=request.POST['number'], event=Event_id).count() num = request.POST['number'] if item == 0: form = AddRiderForm(request.POST) form.user = request.user form.event = Event_id if form.is_valid(): form.save() return render(request, 'web/newrider.html', {'form': AddRiderForm()}) else: return render(request, 'web/newrider.html', {'form': AddRiderForm(), 'error': 'That number is taken, try again with another number', 'item':item}) else: return render(request, 'web/newrider.html', {'form': AddRiderForm(), 'error': 'That number is taken, try again with another number', 'item':Event_id}) else: return render(request, 'web/newrider.html', {'form': AddRiderForm()}) -
Was I supposed to be able to create a question on the website using 'runserver'?
I'm following this Django tutorial. So far I haven't had an issue so far, but now I'm not really sure if I understood it correctly. We created a shortcut function to create questions, but I thought that it was meant to be user-side and when I use 'runserver', on the website there's no such option, only the previously created question. This is the code for the function: def create_question(question_text, days): """ Create a question with the given `question_text` and published the given number of `days` offset to now (negative for questions published in the past, positive for questions that have yet to be published). """ time = timezone.now() + datetime.timedelta(days=days) return Question.objects.create(question_text=question_text, pub_date=time) Did I get it wrong? This function is only admin-sided? It's on 'polls/test.py' and it's outside every class. -
My static files in aws s3 is not loaded in my Django blog
I am working on a small blog with Django. I've deployed it to pythonanywhere but the problem is that all my static files are not loading. When I tried inspecting the the page chrome, it shows that the links are from amazon. Even when I run the collectstatic command, the necessary folders are created in my s3 bucket and the files are copied to the folders. This is the config in my settings.py AWS_ACCESS_KEY_ID = "XXXXXXXXXXXXXXXXXXXXXX" AWS_SECRET_ACCESS_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" AWS_STORAGE_BUCKET_NAME = "XXXXXXXXXXXX" AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazon.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400',} STATICFILES_DIRS= [os.path.join(BASE_DIR, 'static'),] AWS_LOCATION = 'static' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) DEFAULT_FILE_STORAGE = 'myblog.storage_backends.MediaStorage' In the console tab of inspection page, I see www.majestylink.com/:9 GET https://majestylinkbucket.s3.amazon.com/static/css/bootstrap.min.css net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:11 GET https://majestylinkbucket.s3.amazon.com/static/css/music.css net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:13 GET https://majestylinkbucket.s3.amazon.com/static/css/poem.css net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:15 GET https://majestylinkbucket.s3.amazon.com/static/css/home.css net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:17 GET https://majestylinkbucket.s3.amazon.com/static/css/video.css net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:196 GET https://majestylinkbucket.s3.amazon.com/static/js/jquery-3.4.1.min.js net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:197 GET https://majestylinkbucket.s3.amazon.com/static/js/bootstrap.min.js net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:155 GET https://majestylinkbucket.s3.amazon.com/static/img/fb.png net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:159 GET https://majestylinkbucket.s3.amazon.com/static/img/wp.png net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:163 GET https://majestylinkbucket.s3.amazon.com/static/img/ig.png net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:167 GET https://majestylinkbucket.s3.amazon.com/static/img/yb.png net::ERR_NAME_NOT_RESOLVED www.majestylink.com/:171 GET https://majestylinkbucket.s3.amazon.com/static/img/tt.png net::ERR_NAME_NOT_RESOLVED Please what am I not doing right? -
error en heroku at=error code=H10 desc="App crashed" method=GET path="/" host=djangoblog33.herokuapp.com
el error completo es: 2020-11-11T01:39:03.861407+00:00 app[api]: Initial release by user bastanterojo11@gmail.com 2020-11-11T01:39:03.861407+00:00 app[api]: Release v1 created by user bastanterojo11@gmail.com 2020-11-11T01:39:03.982182+00:00 app[api]: Release v2 created by user bastanterojo11@gmail.com 2020-11-11T01:39:03.982182+00:00 app[api]: Enable Logplex by user bastanterojo11@gmail.com 2020-11-11T01:45:17.000000+00:00 app[api]: Build started by user bastanterojo11@gmail.com 2020-11-11T01:45:54.000000+00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/2124a9f1-ff92-4431-8a1e-a2c39d0583e5/activity/builds/57d3eecd-80c1-49e6-bd0b-37268a6ae3df 2020-11-11T01:46:05.941459+00:00 app[api]: Set DISABLE_COLLECTSTATIC config vars by user bastanterojo11@gmail.com 2020-11-11T01:46:05.941459+00:00 app[api]: Release v3 created by user bastanterojo11@gmail.com 2020-11-11T01:48:10.000000+00:00 app[api]: Build started by user bastanterojo11@gmail.com 2020-11-11T01:49:02.116687+00:00 app[api]: Running release v4 commands by user bastanterojo11@gmail.com 2020-11-11T01:49:02.116687+00:00 app[api]: Attach DATABASE (@ref:postgresql-concave-13076) by user bastanterojo11@gmail.com 2020-11-11T01:49:02.130526+00:00 app[api]: Release v5 created by user bastanterojo11@gmail.com 2020-11-11T01:49:02.130526+00:00 app[api]: @ref:postgresql-concave-13076 completed provisioning, setting DATABASE_URL. by user bastanterojo11@gmail.com 2020-11-11T01:49:02.472811+00:00 app[api]: Deploy 54db32d8 by user bastanterojo11@gmail.com 2020-11-11T01:49:02.472811+00:00 app[api]: Release v6 created by user bastanterojo11@gmail.com 2020-11-11T01:49:02.485754+00:00 app[api]: Scaled to web@1:Free by user bastanterojo11@gmail.com 2020-11-11T01:49:07.944708+00:00 heroku[web.1]: Starting process with command `gunircorn django_blog.wsi` 2020-11-11T01:49:09.754226+00:00 app[web.1]: bash: gunircorn: command not found 2020-11-11T01:49:09.805462+00:00 heroku[web.1]: Process exited with status 127 2020-11-11T01:49:09.847279+00:00 heroku[web.1]: State changed from starting to crashed 2020-11-11T01:49:09.851178+00:00 heroku[web.1]: State changed from crashed to starting 2020-11-11T01:49:12.000000+00:00 app[api]: Build succeeded 2020-11-11T01:49:14.978188+00:00 heroku[web.1]: Starting process with command `gunircorn django_blog.wsi` 2020-11-11T01:49:18.067114+00:00 app[web.1]: bash: gunircorn: command not found 2020-11-11T01:49:18.116336+00:00 heroku[web.1]: Process exited with status 127 2020-11-11T01:49:18.157787+00:00 heroku[web.1]: State … -
Converting a Function to CBV for Django Project
I have created a blog project using a Class Based Viewand now I was trying to add the like button to the posts. So, I want to know how to convert the function used in the project to be included in the Class Based View. My question is how to convert the function used in the tutorial to fit in my project to be included in the Class Based View. (It is a learning process for me to also include Comments.) Here is the models.py class Post(models.Model): liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') ...................................... @property def num_likes(self): return self.liked.all().count() LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) date_liked = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.post) Here is the views: class PostListView(ListView): model = Post template_name = "blog/post_list.html" # <app>/<model>_<viewtype>.html ordering = ['-date_posted'] context_object_name = 'posts' paginate_by = 1 class UserPostListView(ListView): model = Post template_name = 'blog/user_posts.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" # <app>/<model>_<viewtype>.html def get(self, request, *args, **kwargs): res = super().get(request, *args, **kwargs) self.object.incrementViewCount() return res def … -
Django dynamic queryset
I have a view which can receive from none to four different filter lookups. Let's say it starts with Model.objects.all() and then if filter_option is not None and filter_option != '' the idea is to add that filter to the queryset. Making a lot of ifs is a solution but it's really ugly. This is what I'm trying but I'm not getting the expected behavior: class CourseList(ListView): model = Course paginate_by = 10 def get_queryset(self, queryset=None): q = self.request.GET.get('q') sort = self.request.GET.get('sort') level = self.request.GET.get('level') qs = Course.objects.all() if q is not None and q != '': qs.filter(Q(title__icontains=q) | Q(description__icontains=q)) if sort is not None and sort != '': qs.order_by(sort) if level is not None and level != '': sq.filter(level=level) return qs For each "if true" condition I want those options added to the queryset. But instead I'm just getting Course.objects.all() as result all the time. -
Download zip file from http api in react, Receiving error: "Unable to expand file.zip. It is an unsupported format"
Thanks in advance for taking a look. I am working on being able to download a zip file from react through a django api request. I am able to click on my pop up that downloads the zip file, but when I double click on the zip file to open, I get this error: "Unable to expand file_name.zip. It is an unsupported format" My response with the zip file seems to be passing correctly to the front end, so I am thinking it may be something wrong with the react code when making the "blob"? Thanks again. Django code: class DownloadZip(APIView): def post(self, request, format=None): # information to find file to create zip profile_name = request.data["profile"] profile_year = request.data["year"] # file path to create zips from path = str(Path(__file__).parent.resolve()) zip_dir = shutil.make_archive(profile_name + profile_year, "zip", path + "profile_name") s = io.StringIO(zip_dir) response = HttpResponse(s, content_type = "application/zip") zip_name = profile_name + profile_year + ".zip" response["Content-Disposition"] = f"attachment; filename={zip_name}" return response React code: downloadZip = async () => { const params = { profile: this.state.profileName, year: this.state.year, }; axios({ url: `${serverUrl}/download_zip`, method: "post", data: params }).then( (res) => { const url = window.URL.createObjectURL(new Blob([res.data],{type:'application/zip'})); const link = document.createElement('a'); link.href = url; … -
saving images on a local files with heroku
Hello i am new to django and I am almost done with my first web development but I have this Problem that I noticed. images are not getting saved on the File that is set for saving images on my local PC and therefor I was wondering if its a problem on my part or heroku dose not work like the localhost. I would be thankful for some explaining and thanks Here is some codes of my project: Settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], ..... STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' displaying the image on an html {% for topic in result %} <div class="card-mb3"> <div class="card-header" style="background-color:lightgrey"> <table class="table"> <tr> <th>Image</th> <th>Title of the topic</th> <th>Edit</th> <th>Delete</th> </tr> <div class="card-body" style="background-color:white"> <tr> <td> {% if topic.image %} <image src="{{topic.image.url}}" style="width:200px"> upload.html {% block content %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} <input type="file" name="document"> <button type="submit"> Upload image <i class="fas fa-upload"></i> </button> </form> {% endblock content %} views.py def upload(request): context = {} if request == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) return render(request, 'learning_logs/upload.html', context) -
How do I update an object that was made with POST in a React front-end... in a Django backend?
I'm trying to follow a tutorial, these are the videos in the series I watched so far: Part 1 Part 2 (Handling Post Requests) Of course you don't want to watch the videos, so here's the project on GitHub: here My method for handling post requests is pretty much the same as his. It looks like this: class CustomForm extends React.Component { handleFormSubmit = async (event, requestType, profileID) => { const postObj = { user_name: event.target.elements.user_name.value, } if (requestType === "post") { await axios.post("http://127.0.0.1:8000/api/create/", postObj) .then(res => { if (res.status === 201) { this.props.history.push(`/`); } }) } else if (requestType === "put") { await axios.put(`http://127.0.0.1:8000/api/${profileID}/update/`, postObj) .then(res => { if (res.status === 200) { this.props.history.push(`/`); } }) } } So I have a question. What if I did it they way he did it, but instead of just posting to the server (posts happen on form submission)... I want to post to the server AND have my backend start asynchronously updating that posted object as soon as it's posted? How would I go about doing that (based off his / my code [kinda identical] ? The closest thing I can think of is using the views.py file to take in … -
Django is useless can't even update db while saving a form
I am trying to save a form but the db doesn't update whenever I upload. I don't know what's happening. Had some issues with django not getting the user_id or setting it to Null when uploading so I changed my views.py and now nothing happens in the db but the upload seems successful . my views.py: from django.shortcuts import render from .forms import UserProfileForm def index(request): if request.user.is_authenticated: return details(request) else: return render(request, 'soc_auth/index.html') def details(request): if request.method == "POST": form = UserProfileForm(request.POST, request.FILES) if form.is_valid(): current_user = form.save(commit=False) current_user = request.user current_user.save() img_obj = form.instance return render(request, 'soc_auth/details.html', {'form': form, 'img_obj' : img_obj}) else: form = UserProfileForm() return render(request, 'soc_auth/details.html', {'form': form}) forms.py from django import forms from django.core.files.images import get_image_dimensions from soc_auth.models import UserProfile class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile #fields = '__all__' fields = ['avatar', 'name', 'description'] def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) #validate dimensions max_width = max_height = 1000 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) #validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', … -
I'm getting an IntegrityError at /post/new/ NOT NULL constraint failed: blog_post.author_id
Im trying to remove the dropdown so that the user can only see his/her username.Image of the author dropdown.[Image that i want to happen][2] The code -
Using django-dbbackup with parameters not working in view
I am trying to make a view for my user to save and restore database using django-dbbackup. I need my user to be able to decide the name of file for saving and the file to be restored using FormView. But commands dbbackup and dbrestore are not accepting parameters when I call them with call_command in view.py, but doing manage.py dbbackup -o mycopy in terminal works. Still learning. error in backup: raise CommandError("Unknown command: %r" % command_name) django.core.management.base.CommandError: Unknown command: 'dbbackup -o mycopy' Is there another way to restore and backup without using terminal? -
Template Not Found
Hey i am new to django and I am almost done with my first project but I am getting a problem when I open my Site with heroku using heroku open in the terminal when the Site open I get an error that my base template is missing. Settings BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')] any html {% extends "learning_logs\base.html" %} ......... error TemplateDoesNotExist at / learning_logs\base.html django.template.loaders.filesystem.Loader: /app/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/learning_logs/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/users/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/bootstrap4/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/admin/templates/learning_logs\base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.7/site-packages/django/contrib/auth/templates/learning_logs\base.html (Source does not exist) If any other code might help please tell me. -
Django makemigrations not finding tables
I have a Django APP that work perfectly fine. I downloaded the repository from Github to a new laptop, but when I try to run: python manage.py makemigrations runserver etc I get django.db.utils.OperationalError: no such table: catalog_categorias_producto Already tried: Deleted db.sqlite3 Deleted all migration files (except __init__) Tried makemigrations again No difference. Any clues? Thanks! -
Deploy Django Server with a built-in Vue.js App built with Wepback on Heroku
I am stuck in the deployement of a vue.js django together on heroku. I have tried to load the code on heroku and the is deployed correctly. The problem is that the frontend isn't loaded correctly but, when I click on view, I receive the the message: "An error occurred in the application and your page could not be served" Following the tips "heroku logs --tail", the terminal shows the messages 2020-11-10T22:08:40.000000+00:00 app[api]: Build succeeded 2020-11-10T22:08:40.477011+00:00 app[web.1]: 2020-11-10T22:08:40.477025+00:00 app[web.1]: > frontend@0.1.0 start /app 2020-11-10T22:08:40.477026+00:00 app[web.1]: > node bundle.js 2020-11-10T22:08:40.477026+00:00 app[web.1]: 2020-11-10T22:08:40.516540+00:00 app[web.1]: internal/modules/cjs/loader.js:969 2020-11-10T22:08:40.516541+00:00 app[web.1]: throw err; 2020-11-10T22:08:40.516542+00:00 app[web.1]: ^ 2020-11-10T22:08:40.516542+00:00 app[web.1]: 2020-11-10T22:08:40.516542+00:00 app[web.1]: Error: Cannot find module '/app/bundle.js' 2020-11-10T22:08:40.516543+00:00 app[web.1]: at Function.Module._resolveFilename (internal/modules/cjs/loader.js:966:15) 2020-11-10T22:08:40.516543+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:842:27) 2020-11-10T22:08:40.516544+00:00 app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12) 2020-11-10T22:08:40.516544+00:00 app[web.1]: at internal/main/run_main_module.js:17:47 { 2020-11-10T22:08:40.516544+00:00 app[web.1]: code: 'MODULE_NOT_FOUND', 2020-11-10T22:08:40.516544+00:00 app[web.1]: requireStack: [] 2020-11-10T22:08:40.516545+00:00 app[web.1]: } 2020-11-10T22:08:40.520609+00:00 app[web.1]: npm ERR! code ELIFECYCLE 2020-11-10T22:08:40.520813+00:00 app[web.1]: npm ERR! errno 1 2020-11-10T22:08:40.521710+00:00 app[web.1]: npm ERR! frontend@0.1.0 start: `node bundle.js` 2020-11-10T22:08:40.521801+00:00 app[web.1]: npm ERR! Exit status 1 2020-11-10T22:08:40.521915+00:00 app[web.1]: npm ERR! 2020-11-10T22:08:40.522006+00:00 app[web.1]: npm ERR! Failed at the frontend@0.1.0 start script. 2020-11-10T22:08:40.522077+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging … -
How to get object with largest number of related objects in django
I have model A(Post): class Post(models.Model): title = models.CharField(max_length=30) and model B(Like): class Like(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) How would I retrieve the Post object with the largest number of likes? -
crispy form not populating with data from primary key
I have a form that I want to send data to from another page. The data is definitely sending as I have a test template tag which populates based on the FK but the form itself won't populate the data. models.py class Project(models.Model): curr_choices = ( ('USD', 'USD'), ('GBP', 'GBP'), ('EUR', 'EUR'), ) production_title = models.CharField(max_length=200, unique=True) budget = models.FloatField() currency = models.CharField(max_length=3, choices=curr_choices, default='USD') distributor = models.CharField(max_length=200) image = models.ImageField(null=True, blank=True, upload_to="static/images") proj_media = models.CharField(max_length=200) licencee = models.CharField(max_length=200) rating = models.CharField(max_length=20) release_date = models.DateField() synopsis = models.TextField() term = models.CharField(max_length=20) territory = models.CharField(max_length=20) writer_spot = models.CharField(max_length=200) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.production_title views.py def update_project(request, pk): update = Project.objects.get(id=pk) if request.method == "POST": form = ProjectForm(request.POST, request.FILES, instance=update) if form.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() return redirect('projects') else: form = ProjectForm() context = { 'form': form, 'update': update } return render(request, "projectsync/create_project.html", context) forms.py class ProjectForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.layout = Layout( PrependedText('production_title', "", placeholder="Example Title"), PrependedText('licencee', "", placeholder="Example Licencee"), PrependedText('distributor', "", placeholder="Example Distributor"), PrependedText('writer_spot', "", placeholder="Example Writer of Spot"), PrependedText('synopsis', "", placeholder="Example Synopsis"), Row( Column('currency', css_class='form-group col-md-2 mb-0'), Column(PrependedAppendedText('budget', "", '.00'), css_class='form-group col-md-10 mb-0'), css_class='form-row' ), Row( Column(PrependedText('term', … -
Django Multiple Forms One Page
I have two forms on one page (enquiry / make a booking). At any one time only one of these two forms will be submitted. This is my current views.py. def contact_us(request): if request.method == 'POST': # booking form if 'timezone' in request.POST: # timezone field only in booking_form booking_form = BookingForm(request.POST, request.FILES) if booking_form.is_valid(): booking_form.save() return redirect('thankyou') else: enquiry_form = EnquiryForm(request.POST, request.FILES) if enquiry_form.is_valid(): enquiry_form.save() return redirect('thankyou') else: booking_form = BookingForm() enquiry_form = EnquiryForm() context = { 'booking_form' : booking_form, 'enquiry_form' : enquiry_form, } return render(request, 'contact_us/contact_us.html', context) It works fine apart from when the form validation fails and it should return an error (for example, I have a datefield and if the user enters a date outside of the accepted range). When this happens I get the following error: local variable 'enquiry_form' referenced before assignment Any help would be greatly appreciated. Thank you. -
Django loses connection to MySQL db after initialization (Docker)
I'm starting to work with Docker, I'm running a Django app in a container, and a MySQL db in another one. Both of them are connected through a docker-compose.yml file. After building the containers, Django migrations run successfully and the application starts properly. However, if I connect to the Django container and execute a command (i.e. python manage.py createsuperuser) an OperationalError is raised saying that it is not possible to connect to the database. What can be the problem? The picture below shows that tables are created in the database (at some point Django does have access to the db) Accessing the 4rs_backend container (Django) with docker exec -it <container id> sh and executing python manage.py createsuperuser raises: docker-compose.yml: version: '3' services: db: image: mysql:5.7 ports: - "7000:3306" environment: MYSQL_PORT: 3306 MYSQL_USER: admin_test MYSQL_ROOT_PASSWORD: '*****' MYSQL_PASSWORD: '*****' MYSQL_DATABASE: forrealstate container_name: mysql_db api: build: backend command: bash -c "BUILD_TYPE='DOCKER' python manage.py makemigrations && BUILD_TYPE='DOCKER' python manage.py migrate && BUILD_TYPE='DOCKER' python manage.py runserver 0.0.0.0:8000" container_name: 4rs_backend volumes: - ./backend:/backend ports: - "8000:8000" depends_on: - db DATABSE config in Settings.py: BUILD_TYPE = os.environ.get('BUILD_TYPE') DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'forrealstate', 'USER': 'admin_test' if BUILD_TYPE == 'DOCKER' else 'root', 'PASSWORD': '********', 'HOST': … -
Prepolate django model form
I have an Event Model and a Nominate Model. The Event Model is a Foreign Key in the Nominate Model. I want my form to be pre-populated with the current event. Any help on how to handle it with the forms or model will be appreciated. class Event(models.Model): """ Model used to store events """ name = models.CharField(max_length=256) class Nominate(models.Model): name = models.CharField(max_length=256) event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name="nominees") -
How do I query django parent and child by a one to many relationship?
So I am fairly new to django and I am trying to create a website keeps a log of who took out their families' dogs last. I have made my models to include tables for each individual post, dog, and their actions that correspond with the posts themselves. I want to make it so that a list of posts will be placed in order of latest to earliest post followed by all of the actions that each dog did (i.e. if there are two dog objects then there will be two action objects that accompany the post). models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Dog(models.Model): name = models.CharField(max_length = 20) class Post(models.Model): walker = models.ForeignKey(User, on_delete = models.CASCADE) time_posted = models.DateTimeField(default = timezone.now) issues = models.TextField(max_length = 300) class Action(models.Model): post = models.ForeignKey(Post, on_delete = models.CASCADE) dog = models.ForeignKey(Dog, on_delete = models.CASCADE) peed = models.BooleanField(default = False) pooped = models.BooleanField(default = False) views.py: from django.shortcuts import render from django.views.generic import ListView, CreateView from .models import Post, Dog, Action from django.http import HttpResponse class ActionList(ListView): def home(request): context = { 'posts': Post.objects.all(), 'actions': Action.objects.all(), 'dogs': Dog.objects.all() } return render(request, 'dog_log_app/home.html', context) main.html: <!DOCTYPE html> … -
My project is not finding my django module
Here is my project's git: https://github.com/DieterClaessens67/SOA I keep getting this error when I do python manage.py runserver: despite executing pip install django in de venv As I already mentioned I am using virtual environments. Here is a quick overview of my project structure for clarity: Can anyone please tell me what is going wrong here? -
Django get OAuth user id while submitting a form (This field is required while uploading)
I'm trying to make an "upload avatar" form for users that are registered through OAuth. If I only have 'avatar' as my choice of fields for the form I get "This field is required" as the response every time. I need a way to get the currently logged in user and submit his id alongside the uploaded avatar. forms.py from django import forms from django.core.files.images import get_image_dimensions from soc_auth.models import UserProfile class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile #fields = '__all__' fields = ['avatar'] #def __init__(self, user, *args, **kwargs): #self.user = user #super(UserProfileForm, self).__init__(*args, **kwargs) def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: w, h = get_image_dimensions(avatar) #validate dimensions max_width = max_height = 1000 if w > max_width or h > max_height: raise forms.ValidationError( u'Please use an image that is ' '%s x %s pixels or smaller.' % (max_width, max_height)) #validate content type main, sub = avatar.content_type.split('/') if not (main == 'image' and sub in ['jpeg', 'pjpeg', 'gif', 'png']): raise forms.ValidationError(u'Please use a JPEG, ' 'GIF or PNG image.') #validate file size if len(avatar) > (20 * 1024): raise forms.ValidationError( u'Avatar file size may not exceed 20k.') except AttributeError: """ Handles case when we are updating the user profile and do not …