Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to setup nginx to site to a Django app over https?
I have an application that I am running with multiple docker containers with a docker-compose file. Two main containers are django_container and nginx_container. I want to force using https for my application but unfortunately, my Nginx config doesn't seem to work. Basically, my gunicorn server seems to be running OK. I can see the http://django:8001 from inside the nginx_container, but I can't see http://example.com from inside it or outside. Here is the content of my Nginx config server { listen 80; server_name example.com; rewrite ^ https://example.com$request_uri? permanent; } server { listen 443 ssl; server_name example.com; ssl_certificate /etc/nginx/certs/example_com.crt; ssl_certificate_key /etc/nginx/certs/cert.key; access_log /log/nginx.access.log main; location / { proxy_pass http://django:8001; proxy_set_header X-Forwarded-Proto $scheme; } error_page 404 /404.html; error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } What am I missing here? Thanks a ton! -
Django rest framework not refreshing template changes
I was trying to update my django rest framework browsable api template, initially trying to change the theme and afterwards changing the navbar branding text, but, after creating the rest_framework/api.html file for the first time, the changes got stuck and the initial changes will not either update nor delete. I've tried deleting the whole proj/app/templates/rest_framework directory, but the changes are still there. I also deleted my browser's cache and cloudflare's cache, restarted Apache 2, and even restarted the server. This is my app directory: website ├── __init__.py ├── admin.py ├── apps.py ├── locale │ └── (more folders) ├── models.py ├── static │ └── (more folders) ├── templates │ ├── anime │ │ ├── detail.html │ │ └── index.html │ ├── (here was the rest_framework directory with the api.html file) │ ├── footer.html │ ├── imports.html │ ├── navbar.html │ └── website │ ├── index.html │ └── welcome.html ├── tests.py ├── urls.py └── views.py My old api.html (the last version before editing) looked like this: {% extends "rest_framework/base.html" %} {% load i18n %} {% block bootstrap_theme %} <link rel="stylesheet" href="https://example.com/static/bootstrap/bootstrap.css" type="text/css"> {% endblock %} {% block branding %} <a class="navbar-brand" rel="nofollow" href="#"> My Project </a> {% endblock %} In the browsable … -
I am getting "Could not parse the remainder: '=="dashboard"' from 'section=="dashboard" error what could be the possible reason for this error?
this is my base.html. I tried replacing == with = .Also, I properly checked if I forgot closing tag but didn't found such problems -
Django Page loading error ?page=undefined
learning pagination and not understanding why page variable is undefined. I can hover over each page object and tool tip shows correct page=page#, each button is numbered correctly as well. This is the function from the view of the app: def projects(request): projects, search_query = searchProjects(request) results = 4 page_number = request.GET.get('page') if page_number == None: page_number = 1 paginator = Paginator(projects, results) try: projects = paginator.page(page_number) except PageNotAnInteger: page_number = 1 projects = paginator.page(page_number) context = { 'projects': projects, 'search_query': search_query, 'paginator': paginator } return render(request, 'projects/projects.html', context) The html code for pagination is as follows: <div class="pagination"> <ul class="container"> {% for page in paginator.page_range %} {% if page == paginator.number %} <li><a href="?page={{page}}" class="btn page-link btn--sub" >{{page}}</a></li> {% else %} <li><a href="?page={{page}}" class="btn page-link">{{page}}</a></li> {% endif %} {% endfor %} </ul> </div> when a page is clicked, the page does not refresh to the correct page or show the current page highlighted, the initial content(1st page) is displayed. When I print the values of the paginator attributes I can see the correct pages generated and objects referenced correctly. Just not understanding why the anchor {{page}} references are not being returned to the view on a GET event. This … -
How to fix the encode error in Django while trying to send an e-mail
Im trying to send an verification e-mail to a new registrated account in Django, but im getting an encode error that I dont know how to fix, please help me to fix it, so then I can succeffuly verify the account aaaaaaaaaaaaaa if DEBUG: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'jamelaumn@gmail.com' EMAIL_HOST_PASSWORD = xxxxx # important else: EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' my urls.py: path('register/', views.account_register, name='register'), my views.py: from django.template.loader import render_to_string from django.utils.encoding import force_bytes from django.utils.http import urlsafe_base64_decode, urlsafe_base64_encode from django.core.mail import EmailMessage from django.conf import settings from django.template.loader import render_to_string def account_register(request): if request.user.is_authenticated: return redirect('account:dashboard') if request.method == 'POST': registerForm = RegistrationForm(request.POST) if registerForm.is_valid(): user = registerForm.save(commit=False) user.email = registerForm.cleaned_data['email'] user.set_password(registerForm.cleaned_data['password']) user.is_active = False email_to = user.email user.save() email_subject = 'Ative sua conta' current_site = get_current_site(request) message = render_to_string('account/registration/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) email_body = message email = EmailMessage( email_subject, email_body, settings.EMAIL_HOST_USER, [email_to]) email.send() return HttpResponse('registered succesfully and activation sent') else: registerForm = RegistrationForm() return render(request, 'account/registration/register.html', {'form': registerForm}) def account_activate(request, uidb64, token): try: uid = urlsafe_base64_decode(uidb64) user = UserBase.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, user.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active … -
Querying django models to include and exclude items
I currently have 2 models as such class Recipe(models.Model): account = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True) name = models.TextField(null=True, blank=True) slug = models.SlugField(null=False, blank=True, unique=True) image_path = models.ImageField(upload_to=MEDIA_URL, null=True, blank=True) description = models.TextField(null=True, blank=True) date_added = models.DateField(auto_now_add=True) class RecipeIngredients(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True) ingredient = models.TextField(null=True, blank=True) quantity = models.CharField(max_length=10, null=True, blank=True) type = models.CharField(max_length=50, null=True, blank=True) I am trying to do a query where if I have a list of say 2 or more items, say ingredients = ["egg", "bacon", "rice"] That it returns to me only the recipes that have exactly egg, bacon, and rice, or less. I was able to do this in a hacky way, but it is really slow and not using the ORM correctly I feel. for i in ingredients: r = RecipeIngredients.objects.filter(ingredient__icontains=i) results.append(r) for result in results: for r in result: recipes.append(r.recipe) for r in recipes: recipeingredients = r.recipeingredients_set.all() for ri in recipeingredients: ingredient = ri.ingredient if ingredient not in ingredients: try: recipes.remove(r) except: print(r) print("end of recipe") Any help on how to make this a more correct query would be appreciated. -
How can i submit initial data in database while migrating in Django?
Info: I want to save the auth-group records while migrating the database in Django. the records which come from auth_groups.json. Maybe my question is similar with others but i don't understand the logic with auth_groups.json. I have multi tenant database but when i create a new tenant i want to be save with init. 0003_auto_20220525_2056.py # Generated by Django 4.0.4 on 2022-05-25 20:56 from django.db import migrations from django.core import serializers fixture_filename = 'fixtures/groups.json' def load_initial_data(apps, schema_editor): fixture = open(fixture_filename, 'rb') auth_group = apps.get_model('auth', 'Group') for obj in auth_group: obj.save() fixture.close() class Migration(migrations.Migration): dependencies = [ ('account', '0002_initial'), ] operations = [ migrations.RunPython(load_initial_data), ] auth_groups.json [ { "model": "auth.group", "pk": 1, "fields": { "name": "admin", "permissions": [] } }, { "model": "auth.group", "pk": 2, "fields": { "name": "producer", "permissions": [] } } ] -
django. The manage.py is not working after migrating mysql table
I install mysql as my database in my django project. I did makemigration and migrate it on the django. After that I wanted to try to run the server, but the python manage.py is not working at all even if there is python stored in my computer. python_version_in_cmd I have the screenshot here where it shows no response at all but pip is responding. django This is my computer environment path computer enviroment path When I was installing mysql the mysql/python was failing, is that the problem? any hints? -
Cannot resolve keyword 'slug' into field. Choices are: id, location, profile_image, stories, twitter, user, user_id, website
I'm trying to create profile page for a user when I click on create profile instead of showing me the edit template that will allowed me to edit all these fields then it throws me an error like this: Cannot resolve keyword 'slug' into field. Choices are: id, location, profile_image, stories, twitter, user, user_id, website i want a user to be able to create profile. How can i solve this problem ? the urls: path('editprofile/<slug:slug>/edit', views.EditProfileView.as_view(), name='editProfile'), the models: class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) profile_image = models.ImageField(upload_to="avatars/") stories = models.TextField(max_length=500,blank=True, null=True) website = models.URLField(max_length=250, blank=True, null=True) twitter = models.URLField(max_length=250, blank=True, null=True) location = models.CharField(max_length=50, blank=True, null=True) the views: @login_required(login_url='login') def profile(request, pk): profiles = Profile.objects.filter(user=request.user) questions = Question.objects.filter(user=request.user) context = {'questions':questions, 'profiles':profiles} return render(request, 'profile.html', context) class EditProfileView(UpdateView): model = Profile fields = ['profile_image', 'stories', 'website', 'twitter', 'location'] template_name = 'edit_profile.html' success_url = reverse_lazy('index') the profile template: <div class="container"> <div class="row"> <a href="{% url 'editProfile' user.id %}" class="btn btn-primary">Create Profile</a> </div> </div> -
Get src of image file stored in dtabase?
I have a dessert model in django with a property called picture: class Dessert(models.Model): name = models.CharField(max_length=100) description = models.TextField(max_length=1000, blank=True) picture = models.ImageField(upload_to ='uploads/desserts-pics/', max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2, validators=[MinValueValidator(1)]) tags = models.ManyToManyField(Tag, related_name="desserts") def __str__(self): return self.name + " ($" + str(self.price) +")" And i want to show the image in my front with react, like this: <img src={dessert.picture}> dessert is an instance of the Dessert model witch i got from a request, but the picture is a file not an image, how the hell do i get the src? sorry, i know it's a silly question but i didn't find the answer anywhere else. -
Access to fetch at **link** from origin 'http://localhost:3000' has been blocked by CORS policy
I'm trying to exchange the authorization code for an access token for a Google Calendar integration. I was following Using OAuth 2.0 for Web Server Applications. The examples shown there were for Flask, but I'm using Django. The problem is, I can't redirect to authorization_url because it says Access to fetch at link from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. @api_view(['GET']) def authorize(request): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES) flow.redirect_uri = 'http://localhost:3000/' authorization_url, state = flow.authorization_url( access_type='offline', include_granted_scopes='true') response = redirect(authorization_url) return response However in my settings.py I have: CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000",] -
Getting a list index out of range and i'm not sure why
I get a index list out of range error and cant figure out why. The error seems to be occurring at the line p2 = 'FLipkart Price: $' + price2[0].text. For some reason the similar code that pertains to the the variable p works fine but not this one. If it helps, I am just trying to make a website that compares prices at amazon and flipkit. I am using python and the Django framework. def search_item(request): item = '' if request.method == 'POST': item = request.POST.get('textfield') wbd = wb.Chrome('/usr/bin/chromedriver') #webdriver_path = '/usr/bin/chromedriver' amazon_url = 'https://www.amazon.com/' flip_url = 'https://www.flipkart.com/' search_url = amazon_url + ("s?k=%s" % (item)) print(search_url) wbd.get(search_url) price = wbd.find_elements_by_class_name('a-price-whole') p = 'Amazon Price: $' + price[0].text l = 'Link: ' + search_url search_url2 = flip_url + ("search?q=%s" % (item)) print(search_url2) wbd.get(search_url2) price2 = wbd.find_elements_by_class_name('_1vC4OE') p2 = 'FLipkart Price: $' + price2[0].text l2 = "Flipkart Link: " + search_url2 return render(request, 'index.html', {'aprice': p, 'alink': l, 'fprice': p2, 'flink': l2}) -
Trying to get access token with django-oauth-toolkit using fetch not working while working using jquery
I'm trying to call endpoint to generate access token using oauth in django it is working when I call the endpoint using jquery but not working when I try to call it with fetch here is the code for fetch fetch(`https://<domain>/o/token/`, { method: 'POST', body:{ grant_type:'password', client_id: "<client-id>", client_secret:"<client-secret>", username:"<username>", password:"<password>" } }) .then(res => res.json()) .then(res => {console.log(res)}); the output is {error: 'unsupported_grant_type'} while when I'm calling it using jquery ajax as below its working $.post({ url:'https://<domain>/o/token/', data:{ grant_type:'password', client_id: "<client-id>", client_secret:"<client-secret>", username:"<username>", password:"<password>" }, success: function(data){ console.log(data); } }) the output is {access_token: '<access-token>', expires_in: 3600, token_type: 'Bearer', scope: 'read write groups', refresh_token: '<refresh-token>'} -
Why is Factory Boy populating Local DB instead of Test DB
I set up ~100 unit test for a django app, and later realized each unit test run was creating test users in my local database, instead of the test database. I found a "solution", but I don't know why it's working. Maybe someone can help. apps/user/tests/factories.py class CompanyFactory(factory.django.DjangoModelFactory): class Meta: model = Company title = fake.name() class UserFactory(factory.django.DjangoModelFactory): class Meta: model = User auth0_id = fake.random_number() email = "unit_test_user@cart.com" company = SubFactory(CompanyFactory) When running a test that uses the factory like this, fake users are being persisted in the DB: When changing the UserFactor inheritance to factory.Factory instead of factory.django.DjangoModelFactory it works fine. Anyone know why this behavior is happening? -
Django Cant query Oracle
I have a Django application, and it works fine. So far, the connection to Oracle seems to be ok. The problems is when I try to query data. I use the objects property and it gives me "ORA-00933: SQL command not properly ended" error. So far I ven looking the query and I think is the problem. Anyway, I try that same query on oracle and sems to be pk print(CONTRIBUYENTES.objects.using('VIALISDB').all().query) SELECT "FGESILDOWN.SILD_DET_CONTRIBUYENTES"."DTCO_FOLIOSOLICITUD" FROM "FGESILDOWN.SILD_DET_CONTRIBUYENTES" Does someone knows the problem? -
How to import a function to a view.py file and launch a server with a basic view in django?
The server works fine when I run python3 manage.py runserver on the VSC terminal But as soon as I try to import a function from a view.py file def hello(request): return HttpResponse("Hello Django - Coder") to the urls.py file the server doesn't work I do the from django.view import hello and I also modify the url by adding the path "hello" of the function urlpatterns = [ path('admin/', admin.site.urls), path('hello/' hello) ] But it doesn't work. Any help would be much appreciated -
Flask in python (jinja2.exceptions.TemplateNotFound)
import smtplib #importing the module from flask import Flask, request from flask import Flask, render_template # importing the render_template function app = Flask(__name__) # home route print(6) @app.route("/") def home(): print(8398383) return render_template('E:/contact.html') print(2) @app.route("/", methods=['POST']) def vals(): print(449483) name = request.form['name'] email = request.form['email'] sub = request.form['subject'] bod=request.form['message'] return render_template('E:/contact.html') if __name__=='__main__': print(4948383) app.run(debug=True) this is my flask code <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>KiddieKingdom - Contact</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta name="keywords"> <meta name="description"> <!-- Favicon --> <link href="img/Kiddiekingdom.png" rel="icon"> <!-- Google Web Fonts --> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Handlee&family=Nunito&display=swap" rel="stylesheet"> <!-- Font Awesome --> <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.0/css/all.min.css" rel="stylesheet"> <!-- Flaticon Font --> <link href="lib/flaticon/font/flaticon.css" rel="stylesheet"> <!-- Libraries Stylesheet --> <link href="lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"> <link href="lib/lightbox/css/lightbox.min.css" rel="stylesheet"> <!-- Customized Bootstrap Stylesheet --> <link href="css/style.css" rel="stylesheet"> </head> <body> <!-- Navbar Start --> <div class="container-fluid bg-light position-relative shadow"> <nav class="navbar navbar-expand-lg bg-light navbar-light py-3 py-lg-0 px-0 px-lg-5"> <!--<img src="" class="logo" style="height: 50px; width: 50px; padding-left: 0%;">--> <a href="" class="navbar-brand font-weight-bold text-secondary" style="font-size: 40px;"> <!--<i class="flaticon-028-kindergarten"></i>--> <span class="text-primary text-center">KiddieKingdom</span> <p class="text-left" style="font-size: xx-small;">Reg. no 532/2021</p> </a> <button type="button" class="navbar-toggler" data-toggle="collapse" data-target="#navbarCollapse"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse justify-content-between" id="navbarCollapse"> <div class="navbar-nav font-weight-bold mx-auto py-0"> <a href="index.html" class="nav-item nav-link">Home</a> <a href="about.html" class="nav-item … -
How do I use UUID from objects in my JS scripts?
Helloo, I'm new here . I don't know if I put the right question but I have a problem In my models.py I have the next field: id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) I'm trying to make a show password and copy to clipboard script in JS for every entry but because I'm using UUID it's not working properly. If I'm using simple ID the scripts are fine. The error: identifier starts immediately after numeric literal template.html {% extends "_base.html" %} {% block content %} {{ entry.id}} {{ entry.password_website }}<br /> {{ decrypted_password }}<br /> {{ entry.name_website }}<br /> {{ entry.url_website }}<br /> {{ entry.login_website}}<br /> <a class="btn btn-dark" href="{% url 'vaults:passwords' %}">Go back<a/> <input id="password-{{ entry.id}}" style="width: auto;" type="password" value="{{ decrypted_password }}" disabled> <button style="font-family: monospace; cursor: pointer;" id="password-button-{{ entry.id}}" onclick="showPassword({{ entry.id }});">show</button> <button style="font-family: monospace; cursor: pointer;" onclick="copyToClipboard({{ entry.id }});">copy</button> <script> function showPassword(id) { var input = document.getElementById("password-" + id); var input_button = document.getElementById("password-button-" + id); console.log(input) console.log(input_button) if (input.type === "password") { input.type = "text"; input_button.text = "hide"; } else { input.type = "password"; input_button.text = "show"; } } function copyToClipboard(id) { var password = document.getElementById("password-" + id).value; var elem = document.createElement("textarea"); elem.value = password; elem.style = … -
filter choices for many to many field in form django
I want "picking_person" to be selectable only from "members" of a Group. I ill trying some init and filters, but i cannot find solution. Profile model does not connected with Group model. Group model have two attributes which are connected to Profile: class Group(models.Model): members = models.ManyToManyField( Profile, blank=True, default=Profile, related_name="members" ) picking_person = models.ManyToManyField( Profile, blank=True, default=Profile, related_name="picking_person" ) forms.py: class ChoosePersonPickingForm(ModelForm): class Meta: model = Group fields = ['picking_person'] views.py: def choose_person_to_pick_players(request, pk): group = Group.objects.get(id=pk) form = ChoosePersonPickingForm(instance=group) group_members = group.members.all() if request.method == "POST": form = ChoosePersonPickingForm(request.POST, instance=group) form.save() return redirect('group', group.id) context = {'form': form} return render(request, "choose-picking-person.html", context) I trying Can you help me to find solution? -
NOT NULL constraint failed: mainsite_customer.user_id
i just wanna get profile with full form or empty form def local_cabinet(request): user_id = request.user.id caruser = Checkout.objects.filter(user=request.user) # form = CheckoutForms() orders = request.user.orderitem_set.all() total_orders = orders.count() ready_order = request.user.order_set.all() customer = Customer.objects.filter(user=request.user) customer_form = CustomerForm() maybe here problem idk if request.method == 'POST': if customer.exists(): form = CustomerForm(request.POST, request.FILES, instance=customer) else: form = CustomerForm(request.POST) if form.is_valid(): form.save() context = { 'caruser': caruser, 'orders': orders, 'total_orders': total_orders, 'ready_order': ready_order, 'cat_selected': 0, 'customer_form': customer_form, 'customer': customer, } return render(request, 'localcabinet.html', context=context) idk why i get this, maybe because not right to sava form i will be thanks you if you can help -
How to replace GeoQuerySet in Django model for Django 2.0+
I am trying to upgrade an old GeoDjango project to user newer versions of software, but I am getting an error when trying to upgrade Django from 1.7.5 to newer than 2.0. Apparently the GeoQuerySet was removed in 2.0. But I am not sure how I should remove it, and what to replace it with. Here is a piece of my models.py with the relevant code. from __future__ import unicode_literals from collections import OrderedDict from django.conf import settings from django.contrib.gis.db import models import clustering class PropertySaleQuerySet(models.query.GeoQuerySet): """ QuerySet with additional clustering methods for the PropertySale objects """ def _single_dot_serialize(self, p): return OrderedDict([ ('id', p.uid), ('type', 'dot'), ('sale_type', p.sale_type), ('latitude', p.geometry.y), ('longitude', p.geometry.x), ]) def _cluster_serialize(self, cluster, num): counts = {} centroid = cluster.centroid if len(cluster.items) < settings.CLUSTER_BREAK: return [self._single_dot_serialize(p) for p in cluster.items] for item in cluster.items: if item.sale_type not in counts: counts[item.sale_type] = 0 counts[item.sale_type] += 1 return [OrderedDict([ ('id', num), ('type', 'cluster'), ('latitude', centroid[1]), ('longitude', centroid[0]), ('extent', cluster.extent), ('chartData', counts) ])] def cluster_saletype(self, bbox_string): x1, y1, x2, y2 = map(float, bbox_string.split(',')) dx = x2 - x1 thresh = dx / settings.CLUSTER_THRESH_DENOM properties = list(self.filter(geometry__isnull=False).only('sale_type', 'geometry')) clusters = clustering.cluster(properties, threshold=thresh, getpoint=lambda p: (p.geometry.x, p.geometry.y)) return sum((self._cluster_serialize(cluster, num) for num, … -
How to run a function every month in Django?
I I Want to Add a certain amount of fees to be added in every individual student account every month. To do that, I need to run a function in the 1st day of month. How do I run a function continuously after every month? -
Wagtail wagtailcore issue "NOT NULL constraint failed: wagtailcore_page.translation_key"
I am getting the error message on any call of Page model save method. django.db.utils.IntegrityError: NOT NULL constraint failed: wagtailcore_page.translation_key One of the Page Models looks like this @register_query_field('home_page') class HomePage(BasePageAbstract): body = StreamField( BasePageAbstract.stream_blocks + [ ], null=True, blank=True ) content_panels = BasePageAbstract.content_panels + [ StreamFieldPanel('body', classname="full") ] parent_page_types = None graphql_fields = [ GraphQLString("body") ] with abstract class class BasePageAbstract(Page): title_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=False, on_delete=models.SET_NULL, related_name='+' ) sub_title_text = models.CharField(max_length=500, blank=True, null=True) stream_blocks = [ ('collection', CollectionBlock()), ("rich_text", blocks.RichtextBlock()), ] content_panels = [MultiFieldPanel([ ImageChooserPanel('title_image'), FieldPanel('sub_title_text', widget=forms.Textarea(attrs={'rows':5})), ])] + Page.content_panels class Meta: abstract = True Django = "==2.2.5" wagtail = "==2.6.1" In my database the table wagtailcore_page and the field translation_key are created. So I think it could be a problem with the uuid creation. I tried deleting and re-migrating the Page models - no success. I also tried updating wagtail - no success. I do not really have a clue on how to get closer to a solution of this problem. I'd appreciate any help. I will supply more info if helpful. Best regards! -
how to read a file from a directory and removing the extension when printing it in django?
I'm building a web app on Django and I've implemented two functions, one to save csv files in a file directory on my PC, and the other is to read these files to view them in the website. My problem is that I want to read csv files from the directory and display them but without the csv extension, I want their names to be the only thing visible, but I keep getting this error FileNotFoundError. this is the function that saves the files to a directory def openDataset(request): if request.method == "GET": return render(request, 'blog/upload_csv_ag.html') if request.FILES.get("file2") is not None: csv_file = request.FILES['file2'] if not csv_file.name.endswith('.csv'): message='The uploaded file has to be CSV. Please try again.' return render(request, 'blog/upload_csv_ag.html',{'message':message}) else: save_path = 'C:/Users/user/Desktop/Fault Detection App/Uploaded_Datasets/' file_name = csv_file.name fs = FileSystemStorage(location=save_path) file = fs.save(file_name, csv_file) else: message='no file is uploaded' return render(request, 'blog/upload_csv_ag.html',{'message':message}) return render(request,'blog/upload_csv_ag.html',{'message':'Dataset Uploaded'}) and the function that reads the files from the directory def read_datasets(request): path = r"C:/Users/user/Desktop/Fault Detection App/Uploaded_Datasets/" test = os.listdir(path) path1, dirs, files = next(os.walk(path)) file_count = len(files) print(file_count) dataframes_list_html = [] file_names = [] index = [] for i in range(file_count): temp_df = pd.read_csv(path+files[i]) print(files[i]) dataframes_list_html.append(temp_df.to_html(index=False)) index.append(i) for item in test: if … -
Page not found (404) mistake after setting media folder django
I am getting Page not found (404) mistake after I set up the media folder as follows in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' then in urls.py: from django.contrib import admin from django.urls import path from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT). After this when I try to run the server, I am getting the following message: Using the URLconf defined in personal_portfolio.URLs, Django tried these URL patterns, in this order: admin/ ^media/(?P<path>.*)$ The empty path didn’t match any of these. Where is the mistake?