Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write tests to test the create view function in django?
I am having a view function for creating a post in my small blogging project, Here's the views.py function for creating a post:- @login_required def post_create(request): form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.author_id = request.user.id instance.save() form.save_m2m() messages.success(request, "Successfully Created") return redirect('blog-home') context ={ "form": form } return render(request, "blog/post_create.html", context) I am trying to write a test script using django's inbuilt TestCase library, here it is:- test.py function:- def testpostcreateview_GET(self): self.client.login(username='testuser', password='secret') response = client.Post.objects.create(title= 'this created by the client',content='this is the content of the blog-post') print(Post.objects.all().count()) # self.assertEquals() self.assertEquals(response, True) I am unable to figure out a way of achiveing it,Or am I missing something or in my above code. -
Accessing a ManyToManyField in template
I am attempting to build a portfolio website and the idea was having a 'Project' model that contains multiple instances of an image. I think I was able to achieve this by using the 'ManyToManyField' relationship. class Image(models.Model): image = models.ImageField(upload_to='media/') class Project(models.Model): title = models.CharField(max_length=32) description = models.TextField(default='', null=False) stack = models.TextField(default='', null=False) image = models.ManyToManyField(Image, related_name='images') def __str__(self): return self.title From messing around a bit with the querying API, I've been able to retrieve the querysets for the images, but I am unsure how to keep those associated with their project and feed them into the context of my view. I already pass in an all() query for my Projects model (which is great), but I want to access the images as well. Basically, I want my HTML template to end up looking like this: {% for project in projects %} <div class="card mx-auto" style="width: 50rem;"> <img class="card-img-top" src="{{ project.images }}" alt=""> // Issue here <div class="card-body"> <p>{{ project }}</p> <h5 class="card-title">{{project.title}}</h5> <p class="card-text">{{project.description}}</p> <p class="card-text">{{project.stack}}</p> </div> </div> {% endfor %} And here is the view: def portfolio_view(request, *args, **kwargs): p = Project.objects.all() for project in p: print('title: ', project.title) print('description: ', project.description) print('stack: ', project.stack) print('images: ', … -
Customizing django logger call levels using filters
I'm new to Django and I've been assign to do a task about loggers. I have in mind a simple logger where INFO messages use a simple format and WARNING messages (and above) use a more complex one. This was my attempt: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'simple': { 'format': '{levelname} {message}', 'style': '{', }, 'verbose': { 'format': '{levelname}: {message} Time: [{asctime}] Module: [{module}] Process: [{process:d}] Thread: [{thread:d}] ', 'style': '{', } }, 'handlers': { 'console_simple': { 'class': 'logging.StreamHandler', 'formatter': 'simple', 'level': 'INFO' }, 'console_verbose': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'level': 'WARNING' } }, 'loggers':{ '': { 'handlers': ['console_simple'], 'level': 'INFO' } } } As you can problably imagine, the problem is that WARNING messages or higher will be logged twice. I've though about using filters, but I couldn't find any undestandable explanation on the documentation. How do I set up a filter for this task? I've never created filters before -
Django subscriber feature
I am creating a django site/platform where the main concept is users can create shops and other users can subscribe to those who have shops open (think Etsy). Trying to implement the subscriber feature and this is a model I have so far for it: class Subscriber(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) sub_shop = models.ForeignKey(Shop, on_delete=models.CASCADE) It works perfect for giving users the ability to subscribe and have the subscribtions listed in their profile and vice versa for shop owners, but for now a user can subscribe to a shop as many times as they want and I would like to prevent this. Idk if there is a constraint to allow multiple subscriber model instances by the same user but not allow for the same exact 'user' and 'sub_shop' instance OR if I am just going on about this in a very bad way! -
Changing docker image throws: psycopg2.errors.UndefinedFile: could not access file "$libdir/postgis-3" error
I am running a dockerized django application with a postgres database that has postgis installed. I am using the official image for that and I build it with docker-compose like so: postgres: container_name: postgres_postgis image: postgis/postgis volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres That worked well. Now I am trying to change this image with the official timescale image that has postgis installed as well (https://hub.docker.com/r/timescale/timescaledb-postgis/). I am changing my docker-compose file like this: postgres: container_name: postgres_postgis_timescale image: timescale/timescaledb-postgis:latest-pg12 volumes: - local_postgres_data:/var/lib/postgresql/data - local_postgres_data_backups:/backups env_file: - ./.envs/.local/.postgres My app builds fine and runs fine, but when I try to access data that use postgis I get this error: django.db.utils.OperationalError: could not access file "$libdir/postgis-3": No such file or directory So I entered my database and tried to upgrade the extension with ALTER EXTENSION postgis UPDATE; but I get extension "postgis" has no update path from version "3.0.1" to version "2.5.3" , so I guess I am up to date. I am quite sure it is connected to this extension but have no idea how I could fix this... Anyone might be able to help me out? Thanks a lot in advance! -
Field 'id' expected a number but got 'User'
I am trying to get the username through POST and filter out the user and save it to the model. Whenever I am trying to migrate I am getting the error "Field 'id' expected a number but got 'User'" def newrequest(requests): if (requests.user.is_authenticated and requests.user.userrank.userstatus == 'Agent'): if requests.method == 'POST': principalamount = requests.POST['principalamount'] interest = requests.POST['interest'] emi = requests.POST['emi'] tenure = requests.POST['tenure'] applicantsalary = requests.POST['applicantsalary'] applicantname = requests.POST['applicantname'] applicantcity = requests.POST['applicantcity'] bankname = requests.POST['bankname'] accountnumber = requests.POST['accountnumber'] age = requests.POST['age'] email = requests.POST['email'] userid = User.objects.filter(email__email=email).values('id') loan = Loan( user = User.objects.get(id= userid), principalamount = principalamount, interest = interest, emi = emi, tenure = tenure, applicantsalary = applicantsalary, applicantname = applicantname, applicantcity = applicantcity, bankname = bankname, accountnumber = accountnumber, age = age, ) loan.save() return JsonResponse({"message": "Loan Requested"}) else: return HttpResponseForbidden() This is my Model: class Loan(models.Model): user = models.OnetoOneField(User, on_delete=models.CASCADE) loanid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) principalamount = models.IntegerField() interest = models.IntegerField() emi = models.IntegerField() tenure = models.IntegerField() applicantsalary = models.IntegerField() applicantname = models.CharField(max_length=300) applicantcity = models.CharField(max_length=25) bankname = models.CharField(max_length=100) accountnumber = models.CharField(max_length=25) age = models.IntegerField(null=True) -
Can't install mysqlclient on Mac OS Catalina
I am using Mac OS Catalina 10.15.7, and I want to install mysqlclient on my virtualenv-django directory but I couldn't. I've tried all possible suggestions but I am still getting the same massive error. Please help me out.. I tried >> pip install mysqlclient Collecting mysqlclient Using cached mysqlclient-2.0.1.tar.gz (87 kB) Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /Users/capstone1/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/jn/yn1khnks19589dh7c51p6z7r0000gn/T/pip-install-pr0_4r66/mysqlclient/setup.py'"'"'; __file__='"'"'/private/var/folders/jn/yn1khnks19589dh7c51p6z7r0000gn/T/pip-install-pr0_4r66/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/jn/yn1khnks19589dh7c51p6z7r0000gn/T/pip-wheel-wrv_jpbq cwd: /private/var/folders/jn/yn1khnks19589dh7c51p6z7r0000gn/T/pip-install-pr0_4r66/mysqlclient/ Complete output (27 lines): running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.14-x86_64-3.8 creating build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb creating build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.14-x86_64-3.8/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.macosx-10.14-x86_64-3.8 creating build/temp.macosx-10.14-x86_64-3.8/MySQLdb clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -I/usr/local/opt/openssl/include -Dversion_info=(2,0,1,'final',0) -D__version__=2.0.1 -I/usr/local/opt/mysql-client/include/mysql -I/usr/local/include -I/usr/local/opt/openssl@1.1/include -I/usr/local/opt/sqlite/include -I/Users/capstone1/include -I/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c MySQLdb/_mysql.c -o build/temp.macosx-10.14-x86_64-3.8/MySQLdb/_mysql.o xcrun: … -
How to pass a variable/value with DeleteView in django urls
is there any way to pass a variable with DeleteView in Django? This is my code: path('category/<int:pk>/delete/', DeleteView.as_view( model=Category, success_url=reverse_lazy('expenses:category-list') ), name='category-delete'), I need to pass a number of related elements in database. I would use queryset.filter() and then pass it to the DeleteView. Is there any way of passing that variable directly to the rendered html or I need to make new view in views.py? I know that I can do {{object}}, but nothing more. -
djrestauth customizing password reset email template does not display template variables
I want to customize the contents of the password reset email template and after doing a lot of searches I have found this. serializers.py from dj_rest_auth.serializers import PasswordResetSerializer class CustomPasswordResetSerializer(PasswordResetSerializer): def get_email_options(self): return { 'email_template_name': 'account/email/password_reset_key_message.txt' } password_reset_key_message.txt {% load i18n %}{% autoescape off %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Hello fro {{ site_name }}! You're receiving this e-mail because you or someone else has requested a password for your user account. It can be safely ignored if you did not request a password reset. Click the link below to reset your password.{% endblocktrans %} {{ password_reset_url }} {% if username %}{% blocktrans %}In case you forgot, your username is {{ username }}.{% endblocktrans %} {% endif %}{% blocktrans with site_name=current_site.name site_domain=current_site.domain %}Thank you for using {{ site_name }}! {{ site_domain }}{% endblocktrans %} {% endautoescape %} settings.py REST_AUTH_SERIALIZERS = { 'PASSWORD_RESET_SERIALIZER': 'accounts.serializers.CustomPasswordResetSerializer' } Email that I receive Hello fro ! You're receiving this e-mail because you or someone else has requested a password for your user account. It can be safely ignored if you did not request a password reset. Click the link below to reset your password. Thank you for using ! So the template variables are not being … -
Adding custom field to django-notifications always returning none on notify.send()
I am trying to add a new field to the Notification model in django-notifications-hq. Currently in my main/models.py i have: class Notification(AbstractNotification): # custom field example unique_uuid = models.CharField(max_length=255,unique=True, null=True) class Meta(AbstractNotification.Meta): abstract = False app_label = 'main' Now in my settings.py file I have: NOTIFICATIONS_NOTIFICATION_MODEL = 'main.Notification' NOTIFICATIONS_USE_JSONFIELD=True I am trying to generate a notification in my views.py by using: notify.send(sender=user, recipient=post.author, verb=message, target=post, \ unique_uuid = notification_create_uuid(...)) However, the notification is not being created correctly and the field is returning "None". How can I set this field in notify.send(), so that the notification is created with that field set? -
Send email from view when testing in Django
So I have a view that sends an emails when it store some data on the database, currently I'm testing but the test returns The email can't be sent that happens when there is an error sending the email, I have checked some answers here but so far no positive results. My code: views.py def update_inventory(self): # code store the data is success context = { 'time': timezone.now() } # render email text email_html_message = render_to_string(BASE_PATH+'/inventory/templates/update_inventory.html', context) email_plaintext_message = render_to_string(BASE_PATH+'/inventory/templates/update_inventory.txt', context) msg = EmailMultiAlternatives( # title: "{title}".format(title="Inventory updated"), # message: email_plaintext_message, # from: "noreply@somehost.local", # to: "email@email.com" ) msg.attach_alternative(email_html_message, "text/html") try: msg.send() except Exception as e: raise serializers.ValidationError({'error':"The email can't be sent"}) return Response({'info':'Inventory successfully updated'}, status=status.HTTP_200_OK) tests.py def test_successfully_update_inventory(self): data = {'product1': 500, 'product2': 200} response = self.client.post(reverse('inventory:update-inventory'), data, format='json') stream_handler = logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) logging.getLogger().info(response) # Prints The email can't be sent Any thoughts about this? Thanks in advance -
Categories and Subcategories showing products for the parent and children
Im doing a ecommerce website with django and I have a problem with categories and subcategories. This are my models: class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null = True) title = models.CharField(max_length= 200, null = True) slug = models.SlugField(max_length=200, null = True) ordering = models.IntegerField(default = 0) class Product(models.Model): name = models.CharField(max_length = 255, null = True) slug = models.SlugField(max_length=200) category = models.ForeignKey(Category, related_name='products', on_delete = models.CASCADE) parent = models.ForeignKey('self', related_name = 'variants', on_delete = models.CASCADE, blank = True, null = True) brand = models.ForeignKey(Brand, related_name='products', null = True, on_delete = models.CASCADE) description = models.TextField(blank = True, null = True) price = models.FloatField(null = True) disccount = models.BooleanField(default = False) disccount_price = models.FloatField(blank = True, null = True) And this is my view: def category_detail(request, slug): category = get_object_or_404(Category, slug=slug) products = category.products.filter(parent = None) context = { 'category': category, 'products' : products } return render(request, 'category_detail.html', context) Okay so what I want to do is if I click the parent category I want to show all the products that their children have and If I click a Children I want to show only the products that he has. So i don't know how to do … -
Pass parameter to cursor.execute in Django
I have the following view definition Django def getEiNumberByFeatures(request): # request should be ajax and method should be GET. if request.is_ajax and request.method == "GET": # get the nick name from the client side. id = request.GET.get("id", None) sqlQuery = """SELECT names FROM Costumer WHERE id = %s """ cursor.execute(sqlQuery, (id)) eiNumbers = cursor.fetchall() context = {"EiNumber": eiNumbers} return JsonResponse(context, status=200) I am getting the following error pyodbc.ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000') Have somebody any idea why this can happens? Even when I am sending the parameter -
Помогите написать Permission django rest framework для бана пользователя
Если пользователь забанен тогда он не сможет смотреть PostDetailAPIView. Нужно написать Permission - IsBanned Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') name = models.CharField(max_length=50) bio = models.TextField(max_length=2000, blank=True, default='') avatar = models.ImageField(upload_to='media', null=True, blank=True) is_moderator = models.BooleanField(default=False, verbose_name=("moderator")) is_ban = models.BooleanField(default=False) is_mute = models.BooleanField(default=False) Views.py class PostDetailAPIView(generics.RetrieveAPIView): queryset = Topic.objects.all() serializer_class = PostDetailSerializer permission_classes = [IsBanned] -
Utilise AJAX & javascript to create a toast with Djangos messaging framework
I have followed a tutorial to utilise AJAX to validate an input field before attempting to submit. I have it working on my django built site; however, I have been using toasts to alert the user to other actions and did not want to get way from this. $("#id_hub_name").focusout(function (e) { e.preventDefault(); // get the hubname var hub_name = $(this).val(); // GET AJAX request $.ajax({ type: 'GET', url: "{% url 'validate_hubname' %}", data: {"hub_name": hub_name}, success: function (response) { // if not valid user, alert the user if(!response["valid"]){ alert("You cannot create a hub with same hub name"); var hubName = $("#id_hub_name"); hubName.val("") hubName.focus() } }, error: function (response) { console.log(response) } }) }) This is my current JS, I want to change the alert function to use toasts instead. In my base.html I use the following to listen for toasts and create them. {% if messages %} <div class="message-container"> {% for message in messages %} {% with message.level as level %} {% if level == 40 %} {% include 'includes/toasts/toast_error.html' %} {% elif level == 30 %} {% include 'includes/toasts/toast_warning.html' %} {% elif level == 25 %} {% include 'includes/toasts/toast_success.html' %} {% else %} {% include 'includes/toasts/toast_info.html' %} {% endif … -
Dependent drop down box in form for every submit render chart, how to update new value in chartjs dataset?
I am working on Django project I write the code for dependent drop down box that can be get values and passed to the backend to call the API/JSON to fetch that data in chartjs, but here if I click submit the chart will appear, for the next time I will select zero value or any other value so the chart is disappeared or new values comes but if I overlay the mouse its showing old data also and new data also, how to update only new values. here is my code HTML: <form id ="new_form" name="new_form" method="POST"> {% csrf_token %} <label for="Question_type">Question Types:</label> <select id="qt_it" name = "select_question_type"> <option value="{{question}}">ALL</option> {% for qt in question %} <option value="{{qt.id}}">{{qt.question_type}}</option> {% endfor %} </select> <label for="Certificate">Certificate:</label> <select id="Certificate" name = "select_certificate"> <option disabled selected = "true"> -- Select certificate -- </option> {% for certificate in certifi %} <option value="{{certificate.id}}">{{certificate.certification_name}} {{certificate.certification_year}}</option> {% endfor %} </select> <label for="state">State:</label> <select id="state_id" data-district-url="{% url 'Dashboard:load_district' %}" name = "select_state"> <option disabled selected = "true"> -- Select State -- </option> {% for state in states %} <option value="{{state.id}}" >{{state.state_name}}</option> {% endfor %} </select> <label for="district">District:</label> <select id="district_id" data-taluk-url="{% url 'Dashboard:load_taluk' %}" name = "select_district"> <option disabled … -
How can I write more columns than defined in header?
I am using Datatables jQuery plugin and I have the following columns in html: <tbody> <td class="test1">elem1</td> <td class="test2" style="display: none;">elem2</td> </tbody> I activate one or the other column from jQuery ( always one ). Problem is that 'datatables' plugin yells error because num of columns from tbody is not equal with num of columns from thead (1 in my case 'cause I only want one to display). Is there a workaround for defining more columns than specified in the header and pass validation ? I am writing the html thought Django's template language. For showing columns I use somthing like this: <select onchange="selectChange(this.value)"> <option>test1</option> <option>test2</option> </select> function selectChange(val) { $(`[class*="test"]`).hide(); $(`[class="${val}"]`).show(); } -
Using CheckBox in Django FilterSet
I can't seem to find any solutions to this issue.. In my models.py I have a class called Course like this: class Course(models.Model): seats_occupied = models.IntegerField(null=True, default=0) seats_available = models.IntegerField(null=True, default=25) # etc... In my filters.py I have this filter for it: class CourseFilter(django_filters.FilterSet): seats_occupied = django_filters.NumberFilter(field_name='seats_occupied', lookup_expr='lt') At this point, I need to enter a number to see if seats_occupied is less than that number. But I would like to just have a CheckBox or Possibly a multiple choice with "open/full" courses, that will only give me the courses that are not full. Is there a good way to accomplish this? -
Docker Set Up mysql db
I was setting up mysql with docker and I observe that without defining environment in docker-compose.xml, file I am able to run mysql . Is this good or I am going wrong ? my docker-compose.xml is db: image: mysql:5.7 restart: always ports: - "3302:3306" and my settings.py file is DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': myproj, 'USER': root, 'PASSWORD': 123123123, 'HOST': 'db', 'PORT': 3306, } } I didn't enter any environment in xml file . If even I do its working same . -
How to serve local CSS files in my Django-Dash-Plotly app
I need to add CSS to my project to enable it to stop conflicting with Bootstrap CSS. I have the exact problem this person is having with fixed columns. The solution is to add this CSS snippet somewhere in my directory: .dash-spreadsheet .row { flex-wrap: nowrap; } My only problem is, I'm an extreme novice when it comes to styling files and I feel completely lost on where to add this snippet into my Django-Dash project. I've read the documentation from Django-Dash for local files Also looked at Dash-Plotly official documentation for adding CSS ... and I'm still confused on where to add the code snippet. For anyone wondering I've tuned my django settings.py to fit the Django-Dash requirements, according to documentation. Here is how my Django project is set-up: app.py is my Dash app that is within my home Django app. stockbuckets folder is the main project folder that holds my settings.py file. I see I am also meant to add serve_locally = True as an in app argument or global variable for DASH_PLOTLY in settings.py. Either method I use just gets my project stuck in HTTP GET... trying to find the local files I'm assuming? Would greatly appreciate … -
Getting data from Shopify to Django
I have an Inventory App that was built in django and I want to extract the data from Shopify to my web app. Basically I want to get the customers info from shopify and show it to my Django app table. How to do this ? Any tips? -
how to use json data in django orm filter
I use in query filter in **kwargs but output query set is None. My code is below: kwargs={"category":["v1","v2","v3"],"tags":["t1","t2"]} obj.filter(**kwargs ) -
Django, Docker and traefik shows 404 on deploy but no error logs - using django-cookiecutter
I recently decided to move my website to use docker along with the template that django-cookiecutter with the goal in mind of easy deployment and easy to setup environments. Localy the project runs fine and I can access the website through the ip address of the virtualmachine on port 8000. But when deploying it to DO with the production.yml file it does not fail, the build and up both run successfull. But when I try access the ip of my droplet I get a 404. The only error that I get is from traefik, SSL related and I don't think this is causing the 404. traefik_1 | time="2020-10-07T16:47:26Z" level=error msg="Unable to obtain ACME certificate for domains \"bgan.be,www.bgan.be\": unable to generate a certificate for the domains [bgan.be www.bgan.be]: error: one or more domains had a problem:\n[bgan.be] acme: error: 403 :: urn:ietf:params:acme:error:unauthorized :: Invalid response from http://bgan.be/.well-known/acme-challenge/4AvrIU9r8F3PwtyrK_6yq8fwHc4CgiHeT_4Vk5Yo0G4 [138.68.98.118]: \"<html>\\r\\n<head><title>404 Not Found</title></head>\\r\\n<body>\\r\\n<center><h1>404 Not Found</h1></center>\\r\\n<hr><center>nginx/1.18.0 (Ub\", url: \n[www.bgan.be] acme: error: 403 :: urn:ietf:params:acme:error:unauthorized :: Invalid response from http://www.bgan.be/.well-known/acme-challenge/gToGrbtaQN5SBFyArzNz8r1SQx8QSB2Wax3_CqzYXCk [138.68.98.118]: \"<html>\\r\\n<head><title>404 Not Found</title></head>\\r\\n<body>\\r\\n<center><h1>404 Not Found</h1></center>\\r\\n<hr><center>nginx/1.18.0 (Ub\", url: \n" providerName=letsencrypt.acme routerName=web-secure-router@file rule="Host(`bgan.be`) || Host(`www.bgan.be`)" Would anyone have any suggestions on why this is happening? been stuck on this for 3 days now and have tried to … -
Why my django server is not running after changing BASE_DIR?
I am getting the following error in Git bash. $ python manage.py run Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 345, in execute settings.INSTALLED_APPS File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 83, in __getattr__ self._setup(name) File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\site-packages\django\conf\__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\NAZIA\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\website\website\website\settings.py", line 72, in <module> 'NAME': BASE_DIR / 'db.sqlite3', TypeError: unsupported operand type(s) for /: 'str' and 'str' When I am trying to run the server it shows this. Can anyone please explain it? -
Django: Save forms cleaned_data with foreign key as session items
I've got a ModelForm with a number of attributes - in the CreateView form_valid method I'm trying to save a users form inputs as session data (which I check for in the get_initial method if they visit the form again) ModelForm: class OrgForm(forms.ModelForm): """Form definition for a Org.""" class Meta: """Meta definition for OrgForm.""" model = Org fields = ( "full_name", "short_name", "feature", "state", "email", ) View: class OrgCreateView(CreateView): "CreateView for OrgForm" model = Org form_class = OrgForm success_url = "/home/" def form_valid(self, form): response = super().form_valid(form) # Set the form data to session variables responses = {} for k, v in form.cleaned_data.items(): responses[k] = v self.request.session["org_form_data"] = responses return super().form_valid(form) def get_initial(self): initial = super(OrgCreateView, self).get_initial() # Check for any existing session data # This is present if they had filled this out # and then came back again later to fill out again if "org_form_data" in self.request.session: # They have data - loop through and fill it out for key, value in self.request.session["org_form_data"]: initial[key] = value return initial Model: class Org(models.Model): """Model definition for Org.""" full_name = models.CharField(max_length=150) short_name = models.CharField(max_length=25, blank=True, null=True) state = models.CharField(max_length=50) is_active = models.BooleanField(default=False) feature = models.ForeignKey(Feature, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) last_updated …