Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Image not uploading in Django Form
I'm trying to create form with an image upload functionality, but it doesn't seem to work. When I select the upload button, it actually selects the image. But when I try to submit the form, it keeps asking me to upload an image. Please, I need someone to help me as soon as possible. Thanks. This is my models.py file. # models.py company_logo = models.ImageField(upload_to='logos/') This is my views.py file. # views.py from django.shortcuts import render, redirect from .models import Opening from .forms import CreateOpeningForm def create(request): form = CreateOpeningForm(request.POST, request.FILES) next = request.GET.get if form.is_valid(): form.save() if next: return redirect(next) return redirect('/') context = {'form': form} return render(request, 'openings/create.html', context) This is my forms.py from django import forms from .models import Opening class CreateOpeningForm(forms.ModelForm): class Meta: model = Opening fields = ( 'title', 'category', 'type', 'restriction', 'application_link', 'description', 'company_name', 'company_hq', 'company_statement', 'company_logo', 'company_website', 'company_email', 'company_description', 'plan' ) This is my create.html <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="mt-8"> <h1 class="text-gray-700 mb-2">Logo <span class="text-red-500">*</span></h1> {{ form.company_logo }} </div> </form> This is my urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('core.urls')), path('admin/', admin.site.urls), path('op/', include('openings.urls')), … -
Can not use "import os "in settings.py(Django3)
I know Django changed import os configuration to path system. but I need to import os configuration in Django 3 based project.so I try to import import os in the settings.py file but I got an error. OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: In Django 3 from pathlib import Path BASE_DIR = Path(file).resolve().parent.parent in Django 2 import os ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(file))) -
AbiWord: [file path/ test] is not a valid file name?
Working on document conversion from docx, doc to pdf. Get to know about Abiword which can convert documents from one file format to others. Using python with the os module which supposes to execute my command. This is working properly files with no spaces files but whenever there is a file with spaces it is giving this error. Tried to print command and checked is it right or wrong, But the command is right. def saveDocx(files, user): destination = Path.joinpath(MEDIA_ROOT, user, "trash") current_doc_files = list() for file in files: fs = FileSystemStorage(location=destination) filename = fs.save(file.name, file) filename = os.path.join(destination, filename) current_doc_files.append(filename) print("doc files---->", current_doc_files) return current_doc_files, destination def convToPdf(current_doc_files, user): current_pdf_files = list() for file in current_doc_files: cmd = "abiword --to=pdf {}".format(file) print("----cmd----", cmd) try: os.system(cmd) pdf_file_name = os.path.splitext(file)[0] + '.pdf' print("converted ", pdf_file_name) current_pdf_files.append(pdf_file_name) except Exception as ex: print("--------Exception--------") print(ex) return current_pdf_files creating web app on pythonanywhere, They have provided Abiword word processor. Have a look to output on When a file with no space doc files----> ['/home/trash/test.docx'] **2020-11-08 06:10:20 ----cmd---- abiword --to=pdf /home/trash/test.docx** 2020-11-08 06:10:21 Failed to connect to Mir: Failed to connect to server socket: No such file or directory 2020-11-08 06:10:21 Unable to init server: Could … -
ModuleNotFoundError ModuleNotFoundError: No module named 'account'
I have added facebook authentication to my django app, but when I click on the Login with Facebook button, I get this error: ModuleNotFoundError: No module named 'account' I have an app called accounts, and it is in my INSTALLED_APPS section of the settings.py Here is my login.html template: {% extends "base.html" %} {% block title %}Log-in{% endblock %} {% block content %} <h1>Log-in</h1> {% if form.errors %} <p> Your username and password didn't match. Please try again. </p> {% else %} <p>Please, use the following form to log-in. If you don't have an account <a href="{% url "register" %}">register here</a></p> {% endif %} <div class="login-form"> <form action="{% url 'login' %}" method="post"> {{ form.as_p }} {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> <p><input type="submit" value="Log-in"></p> </form> <p><a href="{% url "password_reset" %}">Forgotten your password?</a></p> </div> <div class="social"> <ul> <li class="facebook"> <a href="{% url "social:begin" "facebook" %}">Sign in with Facebook</a> </li> <li class="twitter"> <a href="#">Login with Twitter</a> </li> <li class="google"> <a href="#">Login with Google</a> </li> </ul> </div> {% endblock %} I am using the default django login view. Where is the error? -
Check if model instance exists
This thread here describes how to assign None if Model.objects.get() does not exist, using from django.core.exceptions import ObjectDoesNotExist If I want just want to check if some_instance exists in the below code, what is the best way (without importing the librabry ObjectDoesNotExist)? Thanks. some_instance=SomeModel.objects.get(name=some_name) -
NoReverseMatch at /blogs/ 'post' is not a registered namespace
I have started a project with an app called Post with the purpose of making a Blog and after finishing it, I understood the importance of choosing an accurate name for each app so I decided to start a new application and call it blog but now I am trying to fix the errors of name changing. So I fixed all errors except on which I don't know its source: NoReverseMatch at /blogs/ 'post' is not a registered namespace I am not sure if it has to do with the Project's url urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), .............] Blog app urls.py app_name = 'blog' urlpatterns = [ path('', views.home, name='home'), path('blogs/', PostListView.as_view(), name='post-list'), path('blog/<slug:slug>/', PostDetailView.as_view(), name='post-detail'), path('new_blog/', PostCreateView.as_view(), name='post-create'), ] views.py def home(request): return render(request, 'blog/directions.html') class PostListView(ListView): model = Post template_name = "blog/post_list.html" ordering = ['-date_posted'] context_object_name = 'posts' paginate_by = 5 class PostDetailView(DetailView): model = Post template_name = "blog/post_detail.html" class PostCreateView(CreateView): model = Post fields = ['title', 'content'] success_url = '/' template_name = 'blog/post_form.html' # <app>/<model>_<viewtype>.html def form_valid(self, form): return super().form_valid(form) Models.py class Post(models.Model): title = models.CharField(max_length=100, unique=True) content = RichTextUploadingField(null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) ........................................ def __str__(self): return self.title What have I done wrong? -
Save creator for objects created in the Django admin panel
I want to create a few objects directly in Django's admin panel, and in that object automatically save the username of the administrator that have been creating it. Any suggestions of how to do this in the easiest way? Cheers, Peter -
Django - Creating and update interval of function after which function executes
Problem - In a django project of PIZZA cafe. After user ordered pizza , I scheduled a function which will execute after certain interval (say x seconds) to inform user that pizza is now ready to be delivered. But if pizza is ready to be delivered at less than x seconds, How do I update the interval of scheduled function?? I need to identify each and every timer object uniquely so that I can edit or delete a timer object and schedule a function with new interval -
request.method == "POST" not working in Update blog post view
While creating an Update Blog Post view/functionality I got this. I don't know what's wrong my post_update view is working but the if condition (request.method=="POST") is not. I am following this tutorial https://youtu.be/WYvUB_eCPTs?t=1287 views.py def post_update(request, id): title = 'Update' post = get_object_or_404(Post, id=id) form = PostForm(request.POST or None, request.FILES or None, instance=post) author = get_author(request.user) print('After author') if request.method == "POST": print('I am not working') if form.is_valid(): form.instance.author = author form.save() return redirect(reverse("post-list", kwargs={ 'id': form.instance.id })) context = { 'title': title, 'form': form } return render(request, "post_update.html", context) urls.py path('post/<id>/', post, name="post-detail"), path('post/<id>/update', post_update, name="post-update"), path('post/<id>/delete', post_delete, name="post-delete"), path('create/', post_create, name="post-create"), post_update.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% load static %} {% block content %} <div class="col-8 offset-2 mb-5 mt-5"> <h3>{{title}} an Article </h3> {{ form.media }} <form method="POST" action="." enctype="multipart/form-data" novalidate> {% csrf_token %} {{form|crispy}} <button class= "btn btn-primary btn-lg w-50" type="submit">Submit</button> </form> </div> <script src="{% static 'vendor/tiny.js' %}"> </script> {% endblock content %} Console Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. After author [08/Nov/2020 10:05:20] "GET /post/1/update HTTP/1.1" 200 12520 Not Found: /post/1/css/content.css [08/Nov/2020 10:05:23] "GET /post/1/css/content.css HTTP/1.1" 404 3148 [08/Nov/2020 10:05:27] "POST /post/1/ HTTP/1.1" 200 15770 -
How to get error messages from a celery task in Django
I have an API endpoint to allow clients to upload data into the database. In the back-end, a UploadView will check the uploaded file format, and pass the data file to a celery task, by delaying the task and calling it asynchronously. As long as the file is in expected format, the client will get HTTP_202_ACCEPTED response. A potential problem is, what if the data is not accepted during the delayed task? e.g. primary key already existed in database. What's the best way to let API clients be aware of such errors from a celery task? -
django states attibuteError although attribute is assigned
I have a Payment Django model that has a CheckNumber attribute that I seem to be facing issues with, at least whilst mentioning the attribute in the str method. It works just fine on the admin page when creating a Payment instance, but as soon as I called it in the method it gave me the following error message: Request URL: http://127.0.0.1:8000/admin/Vendor/payment/ Django Version: 3.0.7 Exception Type: AttributeError Exception Value: 'Payment' object has no attribute 'CheckNumber' Exception Location: /Users/beepboop/PycharmProjects/novatory/Vendor/models.py in __str__, line 72 Python Executable: /Users/beepboop/Environments/novatory/bin/python3.7 Python Version: 3.7.2 this is my code: class Payment(models.Model): Vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE) Amount = models.DecimalField(decimal_places=2, blank=True, max_digits=8) PaymentDate = models.DateField(name="Payment date", help_text="Day of payment") CheckNumber = models.IntegerField(name="Check number", help_text="If payment wasn't made with check, leave blank", blank=True) def __str__(self): return f"Vendor: {self.Vendor.Name} | Amount: {prettyPrintCurrency(self.Amount)} | Checknumber: {self.CheckNumber}" I would absolutely love any comments/suggestions about the cause of the error -
WSGI error for deploying a django application
i'm currently working on a Django app which I'm trying to host on a Linux server (lightsail AWS) that has the bitnami framework. I'm trying to get it to deploy but I keep running into a module not found error. Here's the error_log file: [Sun Nov 08 01:21:53.532404 2020] [wsgi:error] [pid 14462] [remote 128.14.134.170:56514] mod_wsgi (pid=14462): Failed to exec Python script file '/opt/bitnami/projects/PROJECT/PROJECT/munbase/wsgi.py' [Sun Nov 08 01:21:53.532487 2020] [wsgi:error] [pid 14462] [remote 128.14.134.170:56514] mod_wsgi (pid=14462): Exception occurred processing WSGI script '/opt/bitnami/projects/PROJECT/PROJECT/munbase/wsgi.py'. [Sun Nov 08 01:21:53.532645 2020] [wsgi:error] [pid 14462] [remote 128.14.134.170:56514] Traceback (most recent call last): [Sun Nov 08 01:21:53.532699 2020] [wsgi:error] [pid 14462] [remote 128.14.134.170:56514] File "/opt/bitnami/projects/PROJECT/PROJECT/munbase/wsgi.py", line 16, in <module> [Sun Nov 08 01:21:53.532706 2020] [wsgi:error] [pid 14462] [remote 128.14.134.170:56514] application = get_wsgi_application() [Sun Nov 08 01:21:53.532715 2020] [wsgi:error] [pid 14462] [remote 128.14.134.170:56514] File "/opt/bitnami/python/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Sun Nov 08 01:21:53.532720 2020] [wsgi:error] [pid 14462] [remote 128.14.134.170:56514] django.setup(set_prefix=False) [Sun Nov 08 01:21:53.532728 2020] [wsgi:error] [pid 14462] [remote 128.14.134.170:56514] File "/opt/bitnami/python/lib/python3.8/site-packages/django/__init__.py", line 19, in setup [Sun Nov 08 01:21:53.532733 2020] [wsgi:error] [pid 14462] [remote 128.14.134.170:56514] configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) [Sun Nov 08 01:21:53.532741 2020] [wsgi:error] [pid 14462] [remote 128.14.134.170:56514] File "/opt/bitnami/python/lib/python3.8/site-packages/django/conf/__init__.py",line 83, in __getattr__ [Sun Nov 08 01:21:53.532746 2020] … -
Zappa Django app deployed but custom domain not working
I am working in a Django app and its been successfully deployed with Zappa on AWS. If I use the APIGateway address I can reach the app, but my custom domain is not working. I've already undeployed and deployed a few times. Also I've ran a few times: zappa certify. None of that gave me any kind of error. All of the references I can find show me no solution for this problem. As I see no error of any kind I am lost about what to do. Anyone can help? -
How to implement Google, Facebook and Email login functionality in Django using firebase?
I am developing a mobile app that allows the user to login via Google, Facebook, and email. I am trying to implement it using firebase and firebase admin SDK. What is the proper way to implement this? I need to know more about the implementation login. I have read that social login can be implemented in Django with packages like all-auth. Which is best to implement this? Firebase Admin SDK or all-auth(any other packages, if any). -
Django .Reverse for 'doctor' with no arguments not found. 1 pattern (s) tried: ['doctor / (? P <pk> [^ /] +) / $']
Framework Django. I am trying to create a link to the profile of each user (doctor) by creating an automatic url by his id. an error appears: Reverse for 'doctor' with no arguments not found. 1 pattern (s) tried: ['doctor / (? P [^ /] +) / $'] I suppose I need to add a second parameter to the template link, but I can't figure out that "{% url 'doctor' ??%}" html ..."{% url 'doctor' %}"... view.py def doctor(request, pk): doctors = Doctor.objects.get(pk) return render(request, 'main/doctor.html', {'doctors': doctors}) urls path('doctor/<str:pk>/', views.doctor, name='doctor'), -
How to use django_seed to make manytomany field data
I'd like to make dummy db to check my backend. I used django_seed and faker to fill every single db column. but there is no way to fill manytomany field. How can I use django_seed to make manytomany field coulmn? -
Django Models - Establish a third relationship, between two models where one model reliant on foreign key of other?
John's Shop - Audiences: Audience A, Audience B, Audience C Nicole's Shop - Audiences: Audience D, Audience E for StoreDefaultAudience John's Shop should only be able to choose Audience A, Audience B, Audience C as a default audience for StoreDefaultAudience Nicole's Shop should only be able to choose Audience D, Audience E as a default audience only one StoreDefaultAudience should be allowed per Store stores.models.py class Store(models.Model): store_name = models.CharField(max_length=50) audiences.models.py class Audience(models.Model): audience_name = models.CharField(max_length=50) store = models.ForeignKey(Store, on_delete=models.CASCADE) third relationship that I want to create # only one StoreDefaultAudience should be allowed per Store # the default audiences should only be one of that store's audiences class StoreDefaultAudience(models.Model) default_audience = ? store = ? -
Django form DateTimeField
i created a form for input date and time for user, but this form got a strict format, such dont comfortable for input (000-00-00 00:00:00). Each symbol must writing user self.How i can change this form, so when inputing numbers , this symbols - - - : : : avtomaticaly appeared themselves class Appointment(models.Model): time_appointment = models.DateTimeField() patient = models.ForeignKey( Patient, related_name='patient_to_appointment', null=True, on_delete=models.SET_NULL) doctor = models.ForeignKey( Doctor, related_name='doctor_appointment', null=True, on_delete=models.SET_NULL) complaint = models.CharField(max_length=50, null=True, blank=True)`enter code here` html <form action="" method="POST"> {% csrf_token %} {{form}} <input type="submit" name="submit" /> </form> views.py def create_appointment(request): form = AppointmentForm(request.POST) if form.is_valid(): form.save() return redirect('/') return render(request, 'main/f_appointment.html', {'form': form}) -
Django how to reverse many to many objects sortedm2m
I am using sortedm2m library to keep many to many objects ordered. But how can I get a reversed list of objects, for example, something like gallery.photos.all().order_by("-m2m_table.id")? -
Django: how to show related model fields in template
I'm new in Django 3.0 and I'm lost in this easy question, please help me. I have 2 models: class Product(models.Model): fields... class ProductType(models.Model): product = models.ForeignKey(Product, related_name='product_types', on_delete=models.CASCADE) color = models.Charfield(...) In my template, I would like to show all the related product types and their fields to a specific product: ... {% for product in products %} {{ product.??? }} {% endfor %} Here is my view: class ProductsView(ListView): collection = None model = Product paginate_by = 6 template_name = 'shop/product/list.html' context_object_name = 'products' def get_queryset(self): products = Product.objects.filter(available=True) collection_name = self.kwargs['collection_name'] if 'collection_name' in self.kwargs else None if collection_name: collection = get_object_or_404(Collection, name=collection_name) products = products.filter(collection=collection) return products def get_context_data(self): context = super().get_context_data(**self.kwargs) context['notification'] = Notification.objects.all() if 'collection_name' in self.kwargs: context['collection'] = get_object_or_404(Collection, name=self.kwargs['collection_name']) context['collection_name'] = self.kwargs['collection_name'] context['collections'] = Collection.objects.all() return context Thank you -
Django. How to correctly save time & timezones
I have this code that behaves in a rather strange way and opens the question, how should I deal with timezones? So, first I have a datetime object I build from the info a user posts: time_zone = request.POST.get("time_zone") date_start = request.POST.get("date_start") time_day = request.POST.get("time_day") time_zone_obj = pytz.timezone("Etc/" + time_zone) # GMT + 2 in this example date_start = datetime.strptime(date_start, "%d/%m/%Y") date_start = date_start.replace(tzinfo=time_zone_obj) time_day = datetime.strptime(time_day, "%I:%M %p") date_start = date_start.replace(hour=time_day.hour, minute=time_day.minute) ... event.date_start = date_start event.save() print("event.date_start.hour:%s" % event.date_start.hour) return redirect("event_detail", event_id=event.id) This prints event.date_start.hour:6. Then, inmediatlty after saving the object and printing the hour, it redirects to the event_detail view, very simple: def event_detail(request, event_id): event = get_object_or_404(Event, id=event_id) print("event.date_start.hour:%s" % event.date_start.hour) ... And it prints event.date_start.hour:8. I don't understand why. Plz note that I printed the hour after I saved the object and then after I retrieved it in the other view. It has a difference of two hours that must have something to do with the timezone the user selected (GMT + 2). Why is this? Which is the best way to save this data? The user submits "6:00 AM" + "GMT+2" in the form and then later when I want to show the time … -
django-rest-framework get the timestamp since the object created through serialization
I need to get the time since a post object was created. While surfing the internet I have found the following implementation and it gives me the following error Adding @property to models post object class Post(models.Model): timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) @property def timesince(self): return timesince.timesince(self.timestamp) I do not know how the django.utils timesince works, if you know - give me a hint class PostSerializer(serializers.ModelSerializer): timesince = serializers.DateTimeField() class Meta: model = Post fields('__all__') I get the following AttributeError Got AttributeError when attempting to get a value for field `timesince` on serializer `PostSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Post` instance. Original exception text was: 'NoneType' object has no attribute 'year'. -
Importing and creating pages in Django / Wagtail
Although Wagtail and Django seem to be very efficient and sophisticated frameworks, they do not offer any simple way of importing (i.e bulk creating) pages. I have tried dozens of suggestions to do so (eg 1, eg 2, eg 3, eg 4, etc). I've also tried CodeRedCMS (which is based on Wagtail), but it offers a very rudimentary function which have so far not helped me. Gazmans solution in this post seemed very efficient but I could not figure out exactly how to go about solving the issue. So my question is simple: If I have a csv/json file with thousands of rows, where each row represents a post for a specific Page Model I've created in Wagtail, how do I import it to Wagtail? Any example with psuedo code would be immensely appreciated. The only solution that I did (almost) succeed with was by using DataGrip and directly import data into the table, but then Wagtail did not register the entries for some reason. -
Django foreign key not getting data
I have two tables defined in my models: class Products(models.Model): productsid = models.AutoField(primary_key=True) product_number = models.CharField(db_index=True, max_length=15) title = models.CharField(max_length=255, default=None, null=True, blank=True) date = models.DateField(db_index=True, default=datetime.date.today, null=True, blank=True) class ProductFlag(models.Model): product_number = models.CharField(db_index=True, max_length=15) company = models.ForeignKey(Company, db_index=True, on_delete=models.SET_NULL, null=True) productid = models.ForeignKey(Products, db_column='productsid', db_index=True, on_delete=models.SET_NULL, null=True) I want to get the the 'title' from Products when I query ProductFlag. In my views, I make this query: productflags = ProductFlag.objects.filter(company__companyid=self.kwargs.get('company_id')).order_by('product_number') I thought that I could then reference the title field in my template by looping through {% for product in productflags %} and grabbing {{ product_number.productid.title }}, but I get nothing at all. Looking at it in the Django shell, it seems that my productid is always "None" (and my database definitely had data in productsid). I have no issue with the company foreign key. What am I doing wrong? Thanks-- Al -
Trouble deploying django app to AWS lambda using zappa
I am trying to deploy my django app to AWS Lambda. I have viewed many tutorials on how to do so. However, whenever I run zappa deploy, I get the following error at the end: Deploying API Gateway.. Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 502 response code. Running zappa tail gives me the following: [1604786373569] [DEBUG] 2020-11-07T21:59:33.569Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc Read environment variables from: /var/task/my_cool_project/.env [1604786373570] [DEBUG] 2020-11-07T21:59:33.569Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'SECRET_KEY' casted as 'None' with default '<NoValue>' [1604786373582] [DEBUG] 2020-11-07T21:59:33.582Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'DB_ENGINE' casted as 'None' with default '<NoValue>' [1604786373582] [DEBUG] 2020-11-07T21:59:33.582Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'DB_NAME' casted as 'None' with default '<NoValue>' [1604786373582] [DEBUG] 2020-11-07T21:59:33.582Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'DB_USER' casted as 'None' with default '<NoValue>' [1604786373582] [DEBUG] 2020-11-07T21:59:33.582Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'DB_PASSWORD' casted as 'None' with default '<NoValue>' [1604786373582] [DEBUG] 2020-11-07T21:59:33.582Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'DB_HOST' casted as 'None' with default '<NoValue>' [1604786373582] [DEBUG] 2020-11-07T21:59:33.582Z 1a7e8cd4-1bf2-4af4-b11b-2baa6c6691dc get 'DB_PORT' casted as 'None' with default '<NoValue>' [1604786374005] [ERROR] NameError: name '_mysql' is not defined Traceback (most recent call last): File "/var/task/handler.py", line 609, in lambda_handler return LambdaHandler.lambda_handler(event, context) File "/var/task/handler.py", line 240, in lambda_handler handler = cls() File "/var/task/handler.py", line 146, in __init__ wsgi_app_function = get_django_wsgi(self.settings.DJANGO_SETTINGS) File "/var/task/zappa/ext/django_zappa.py", line …