Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Synchronized Model instances in Django
I'm building a model for a Django project (my first Django project) and noticed that instances of a Django model are not synchronized. a_note = Notes.objects.create(message="Hello") # pk=1 same_note = Notes.objects.get(pk=1) same_note.message = "Good day" same_note.save() a_note.message # Still is "Hello" a_note is same_note # False Is there a built-in way to make model instances with the same primary key to be the same object? If yes, (how) does this maintain a globally consistent state of all model objects, even in the case of bulk updates or changing foreign keys and thus making items enter/exit related sets? I can imagine some sort of registry in the model class, which could at least handle simple cases (i.e. it would fail in cases of bulk updates or a change in foreign keys). However, the static registry makes testing more difficult. I intend to build the (domain) model with high-level functions to do complex operations which go beyond the simple CRUD actions of Django's Model class. (Some classes of my model have an instance of a Django Model subclass, as opposed to being an instance of subclass. This is by design to prevent direct access to the database which might break consistencies and … -
Django generic relations, unique together and abstract models
I have a Tag model and an intermediate model to relate it class Tag(models.Model): name = models.CharField(max_length=255) slug = models.CharField(max_length=255, blank=True) class TagIntermediate(models.Model): # Relation to custom content model content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() customcontent = GenericForeignKey('content_type', 'object_id') # Relation to tag tag = models.ForeignKey(Tag, on_delete=models.CASCADE) class Meta: unique_together = ["content_type", "object_id", "tag"] I add this to an abstract base class class BaseModel(models.Model): blog_tags = GenericRelation('TagIntermediate') class Meta: abstract = True And then I define two models derived from it class ModelOne(BaseModel): model_one_field = models.CharField() class ModelTwo(BaseModel): model_two_field = models.CharField() When I now create a Tag object and add it to a ModelOne object and a ModelTwo object, then I get the message triggered by my "unique together" definition: The combination of content_type, object_id and tag does already exist. Why? ModelOne and ModelTwo should be two different content_types, right? Or did I forget something? I`m using Django Version 3.0.4 -
Displaying data in Django by grouping
Basically, I have worked on this project and I am stuck in displaying the data according to my needs on the html page. Right now all that is shown is the 0-4 data but I'm unsure of how to show it correctly. For the children: I want it to show the user's children. For the timeline: Depending on which child is selected, the timeline table will show the data from the specific child.I want to group the data by age range (the column headers) and then when clicked, it will show the pdfs associated with the current timeline cell. My views file: def timeline(request): timeline = Timeline.objects.all() return render(request, 'timeline.html', { 'timeline': timeline }) My model file: HEADER_CHOICES = [ ('Financial Support', 'Financial Support'), ('Educational Support', 'Educational Support'), ('Governmental Support', 'Governmental Support '), ('Charity Support Groups', 'Charity Support Groups'), ('Therapy Support', 'Therapy Support '), ('Transport Support', 'Transport Support ') ] AGE_CHOICES = [ ('0-4', '0-4'), ('4-11', '4-11'), ('11-18', '11-18'), ('18-25', '18-25') ] class Timeline(models.Model): header = models.CharField(max_length=30, choices=HEADER_CHOICES) age = models.CharField(max_length=6, choices=AGE_CHOICES) child = models.OneToOneField(Children, on_delete=models.CASCADE) class Pdf(models.Model): pdf = models.FileField(upload_to='timelinepdfs') timeline = models.ForeignKey(Timeline, on_delete=models.CASCADE) My html page: {% extends 'pages/home_page.html' %} {% block content %} <style> .rightMenu { position:relative; … -
Django ModelForm ignores the data supplied via form and saves a an existing record
Here are the files, forms.py from django.forms import ModelForm from .models import * class NewCustomer(ModelForm): class Meta: model = Customer fields = ('name', 'mobile_number', 'email', 'address') Views.py from django.shortcuts import render, get_object_or_404, redirect from .models import * from .forms import * # Create your views here. def customers(request): customers = Customer.objects.all().order_by('id') return render(request, "customers.html", {'customers': customers, 'custactive': "active"}) def customer_details(request, pk): customer = get_object_or_404(Customer, pk=pk) return render(request, "customer_details.html", {'customer': customer}) def new_customer(request): if request.method == 'POST': form = NewCustomer(request.POST) if form.is_valid(): customer = form.save(commit=False) customer.name = request.user customer.mobile_number = request.user customer.email = request.user customer.address = request.user customer.save() return redirect ('customers') else: form = NewCustomer() return render(request, "new_customer.html", {'form': form}) Can someone tell me what's wrong with the code? Understandably I need to save new data that I supply with the form. -
Obtaining the fields using the ListView class from Django
I'm learning to manage the ListView class from django, obtain the data is really easy. from django.views.generic import ListView from .models import Fleet class fleet_bbdd_view(ListView): template_name = 'data_app/fleets-bbdd.html' paginate_by = 20 model = Fleet context_object_name = 'FleetsList' But what I can't find is how to obtain the fields of my model and pass they in my context object. Is possible to do this using the ListView class ? I know how to obtain it, in a normal function, but if it is possible I prefer to use ListView class. def getData(request): cols = [i.name for i in Fleet._meta.get_fields()] ctx = {'Cols':cols} return JsonResponse(ctx) Can somebody help me? Thank you very much. -
My Django is showing me importError am i doing it wrong
i tried running my django project on the Virtual Studio IDE , created a virtualEnv, but it does not import anything from the django framework, it always underline the "from" with red indicators.this is the error message am getting ..please i need your help because i still don't know why its happening -
Passing parent object into CreateView for a child object
I'm creating a dashboard to edit a tour app. Per tour I have a child record in which I define steps. The 2 models look like this: models.py class Tour(models.Model): tour_id = models.CharField(primary_key=True,unique=True, max_length=10) country = models.ForeignKey(Countries, models.DO_NOTHING, db_column='country') language = models.ForeignKey(Language, models.DO_NOTHING, db_column='language') lastupddtm = models.DateTimeField(default=timezone.now) productid = models.CharField(max_length=50) title = models.CharField(max_length=50) description = models.CharField(max_length=100) descrlong = models.CharField(max_length=1000) live = models.CharField(max_length=1) image = models.ImageField(upload_to=upload_tour_image, storage=OverwriteStorage(), blank=True, null=True) class Meta: db_table = 'tour' verbose_name_plural = "tour" def get_language_flag(self): return self.language.flag.url def __str__(self): return str(self.tour_id) + ' - ' + str(self.title) + ' - ' + str(self.description) class Toursteps(models.Model): # tour_id = models.OneToOneField(Tour, models.DO_NOTHING, db_column='tour_id') tour = models.ForeignKey(Tour, related_name='toursteps', on_delete=models.CASCADE) step = models.IntegerField(unique=True) title = models.CharField(max_length=50) description = models.CharField(max_length=100) descrlong = models.CharField(max_length=1000) audiotext = models.TextField() latitude = models.FloatField() longitude = models.FloatField() radius = models.FloatField() image = models.ImageField(upload_to=upload_tour_step_image, blank=True, null=True) class Meta: db_table = 'tourSteps' verbose_name_plural = "tourSteps" def __str__(self): return str(self.tour) + "|" + str(self.step) After I created a Tour, I go to a detail page. From there I can click a link to add a step for this tour. This is where the problem is. I pass the tour_id as a variable into the url, but I can't find a … -
Best way to create models for shopping lists in Django
I am thinking how to create models in Django when designing a shopping list. So basically I want to have Shopping Item and Shopping List. Shoping Item can be added to different shopping lists multiple times. Could you please advise on that? -
Django - 'tuple' object has no attribute 'status_code'
I'm trying to save some data to my database, but I keep getting the error. 'tuple' object has no attribute 'status_code'. I'm not entirely sure where i'm going wrong . Models.py class Task(models.Model): board = models.ForeignKey(Board, on_delete=models.CASCADE) admin = models.ForeignKey(User, on_delete=models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField() assigned_to = models.CharField(max_length=30) def save(self, *args, **kwargs): self.slug = slugify(self.text) super(Task, self).save(*args, **kwargs) def __str__(self): return self.text Form.py class CreateNewTask(ModelForm): text = forms.CharField(max_length=300, help_text="Please enter task: ") assigned_to = forms.CharField(max_length=30, help_text="Assigned to: ") complete = forms.BooleanField() slug = forms.CharField(widget=forms.HiddenInput(), required=False) class Meta: model = Task fields = ( 'text', 'assigned_to', 'complete') views.py def createTask(request): form = CreateNewTask() if request.method == "POST": form = CreateNewTask(request.POST) if form.is_valid(): temp = form.save(commit=False) temp.board = Board.objects.get(id=id) temp.save() return redirect("/dashboard") return(request, 'boards/create_task.html', {'form':form}) -
Issue with dropdown submitting selected value - Django/Python
I am trying to get the selected value in the dropdown to add to the cart. The way I have it prints out different dropdowns but submits the data into the cart. I just want one dropdown that submits the selected value. Thank you. {% for product in products %} <form class = 'pull-right' method ='GET' action='{% url "update_cart" product.slug 1 %}'> <select id="menulist"> <option>{{ product.name }}: ${{ product.price }}</option> {% endfor %} </select> <button type = 'submit' class ="btn btn-info btn-md" class ='pull-right'>Add To Order</button> </form> -
django.db.utils.ProgrammingError: relation "fdiary_fdiary" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "fdiary_fdiary"
i did everything used python manage.py migrate, etc. But when i click on my model in django admin panel it shows this error. ProgrammingError at /admin/fdiary/fdiary/ relation "fdiary_fdiary" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "fdiary_fdiary" ^ Request Method: GET Request URL: http://127.0.0.1:8000/admin/fdiary/fdiary/ Django Version: 3.0.4 Exception Type: ProgrammingError Exception Value: relation "fdiary_fdiary" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "fdiary_fdiary" ^ Exception Location: J:\Program Files\Python3.8\lib\site-packages\django\db\backends\utils.py in _execute, line 86 Python Executable: J:\Program Files\Python3.8\python.exe Python Version: 3.8.2 Python Path: ['C:\Users\Dell\diary\diary', 'J:\Program Files\Python3.8\python38.zip', 'J:\Program Files\Python3.8\DLLs', 'J:\Program Files\Python3.8\lib', 'J:\Program Files\Python3.8', 'C:\Users\Dell\AppData\Roaming\Python\Python38\site-packages', 'J:\Program Files\Python3.8\lib\site-packages'] Server time: Fri, 3 Apr 2020 20:15:51 +0530 Meta:- ALLUSERSPROFILE 'C:\\ProgramData' APPDATA 'C:\\Users\\Dell\\AppData\\Roaming' COLORTERM 'truecolor' COMMONPROGRAMFILES 'C:\\Program Files\\Common Files' COMMONPROGRAMFILES(X86) 'C:\\Program Files (x86)\\Common Files' COMMONPROGRAMW6432 'C:\\Program Files\\Common Files' COMPUTERNAME 'DESKTOP-S6NQ606' COMSPEC 'C:\\Windows\\system32\\cmd.exe' CONTENT_LENGTH '' CONTENT_TYPE 'text/plain' CSRF_COOKIE 'mNHRnYHHB1kzOdnahlwlppBHiLEKYeO0ghFTgshaQGSXzzbS6aU5TI1rnpkWa9vT' DJANGO_SETTINGS_MODULE 'diary.settings' DRIVERDATA 'C:\\Windows\\System32\\Drivers\\DriverData' GATEWAY_INTERFACE 'CGI/1.1' HOMEDRIVE 'C:' HOMEPATH '\\Users\\Dell' HTTP_ACCEPT 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' HTTP_ACCEPT_ENCODING 'gzip, deflate' HTTP_ACCEPT_LANGUAGE 'en-US,en;q=0.5' HTTP_CONNECTION 'keep-alive' HTTP_COOKIE ('csrftoken=mNHRnYHHB1kzOdnahlwlppBHiLEKYeO0ghFTgshaQGSXzzbS6aU5TI1rnpkWa9vT; ' 'sessionid=amcqamjjcw9chtndh5nzib8nfdv8n1yy; ' 'PGADMIN_INT_KEY=fc56bb57-0d57-4b35-8b29-282be1e4197b; ' 'pga4_session=d8dcf70d-50e4-4474-9aef-6e057e2a6216!P0ZEZvLq08QDIa+4HpmE8XSwdWE=; ' 'PGADMIN_LANGUAGE=en') HTTP_DNT '1' HTTP_HOST '127.0.0.1:8000' HTTP_REFERER 'http://127.0.0.1:8000/admin/' HTTP_UPGRADE_INSECURE_REQUESTS '1' HTTP_USER_AGENT 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0' LANG 'en_GB.UTF-8' LOCALAPPDATA 'C:\\Users\\Dell\\AppData\\Local' LOGONSERVER '\\\\DESKTOP-S6NQ606' NUMBER_OF_PROCESSORS '4' ONEDRIVE 'C:\\Users\\Dell\\OneDrive' ONEDRIVECONSUMER 'C:\\Users\\Dell\\OneDrive' OS 'Windows_NT' PATH ('J:\\Program Files\\Python3.8\\Scripts\\;J:\\Program ' … -
Unable to find static files - Joined path located outside of base path components
Django noob here. My static files are working fine using my local development server, but as soon as I pushed changes to my production server on A2, it could no longer find my static files. For example, it can't find a js file at: https://mywebsite.com/static/js/jquery.waypoints.min.js The file actually exists at: https://mywebsite.com/project_root/static/js/jquery.waypoints.min.js This corresponds to: /home/user/public_html/project_root/static In my settings.py I have: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) STATIC_ROOT = os.path.join(BASE_DIR, 'public') When printed, Staticfile_dirs is /home/user/public_html/project_root/static, which seems right. but once I run python manage.py findstatic js/infinite.min.js It gives me the error django.core.exceptions.SuspiciousFileOperation: The joined path (/js/infinite.min.js) is located outside of the base path component (/home/user/public_html/project_root/static) Can someone help me understand what i'm missing? -
Django forms.ChoiceField to be dynamically created based
Im building a website with django where a user could create a shop > choose maximum one of each category > choose multiple products for each category; in that order I have a DetailView which allows them to see the details of the shop and create a category underneath it. I`m using FormMixin to allow them create a category, and a ChoiceField for the type of category. What I want: Let them choose only from the categories they didnt choose in the past, eg: I have 3 categories: Woodworks, Food, Tools; if they already have added a Tools category to their shop, they should be able to choose it again (i want the form not display it at all) My views: class OrganizationDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView, FormMixin): model = Organization queryset = Organization.objects.all().prefetch_related() template_name = 'org/org_view.html' form_class = CategoryForm def test_func(self): org = self.get_object() if self.request.user.profile == org.owned_by: return True return False def get(self, request, *args, **kwargs): # getting the post to display self.object = self.get_object() context = self.get_context_data() categories = Category.objects.filter(org=self.object).values_list('cat_name') context['categories'] = [] for category in categories: context['categories'].append(*category) return self.render_to_response(context) def post(self, request, *args, **kwargs): pk = self.get_object().serializable_value('pk') org_id = Organization.objects.get(org_id=pk) cat_name = self.request.POST.get('cat_name') new_category = Category.objects.create(org=org_id, cat_name=cat_name) return … -
how to use django template language inside script tag using django-jsRender
As I know, there is no way to use Django template language inside Javascript block so I searched for a way how to do it, I found a Django app on GitHub called Django-jsrender but unfortunately, there isn't enough documentation for this app and when I tried to use it I couldn't and this is my code: -
Django serializer "field is required"
I want a serializer to return all the distinct countries. It just query's the db and returns it. But it always return "field is required" on the "countries" field. This is my serializer: class AdminCountrySiteSerializer(serializers.ModelSerializer): countries = serializers.ListField() class Meta: model = Site fields = ["countries"] def get_countries(self): return list( Site.objects.values_list("country", flat=True) .order_by("country") .distinct() ) test class: def test_get_all_distinct_countries(self): self.client.force_login(self.admin_user) url = reverse("admin-site-countries") response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(len(response.data["countries"]), 3) view: class AdminSiteCountryView(GenericAPIView): def get_permissions(self): return IsAuthenticated(), IsSoundTalksCS() def get_serializer_class(self): return AdminCountrySiteSerializer @swagger_auto_schema( responses={200: openapi.Response(_("Successfully fetched all the countries."),)} ) def get(self, request): """ GET all distinct countries """ serializer_class = self.get_serializer_class() # serializer = serializer_class(data=request.data) serializer = serializer_class(data={"request": request}) serializer.is_valid(raise_exception=True) return Response(data=serializer.data, status=status.HTTP_200_OK,) -
Django Ajax not updating data properly
I am trying to create a like button for my posts in my post list, however, i need to refresh the page every time for the number of likes and button to change. I do not know what's causing this behavior as I am sending all the posts to the post list html file in my view. My 'likes' is a ManyToMany field for the Post model. my post_like view: @login_required def post_like(request,id): data = dict() post = get_object_or_404(Post, id=id) user = request.user if request.method == 'POST': if post.likes.filter(id=user.id).exists(): post.likes.remove(user) else: post.likes.add(user) posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) return JsonResponse(data) my ajax javascript code: $(document).ready(function (e) { $(document).on("click", "#likeBtn", function (e) { e.preventDefault(); var pk = $(this).attr("value"); var tk = $(this).attr("data-token") $.ajax({ type: "POST", dataType: 'json', url: $(this).attr("data-url"), data: {'id':pk, 'csrfmiddlewaretoken': tk}, success: function (data){ $("#post-list div").html(data.posts); }, error: function(rs, e){ console.log(rs.responeText); }, }); }); }) Thanks for all the help in advance! -
Django Logging SystemLogHandler how to encrypt
I use logging.handlers.SysLogHandler in my Django app. I need encrypted data whenever log occurs and send it after encryption. So, do you have any suggestion or solution for this? -
How to save a serial number generated in alert message during form submission in database?
views.py from django.contrib import messages import datetime import random def personal_detail(request): now=datetime.datetime.now() messages.success(request,now.strftime("SKPMMVY%Y%m%d%H%M%S")+str(random.randint(0,99))+str(":\tYour form has been submitted successfully")) apply_online.save() return render(request,'users/applyonline.html') I want to save the serial number that is being generated i've saved others by creating their view like idcard=request.POST.get('idcard') and respectively created their model as idcard=models.CharField(max_length=100,blank=True, null=True) I'm just confused on how I can do the same for messages? -
How can I use a single enum for django model and graphql mutation arguments?
I've defined Django models with fields containing text choices corresponding to enums. The GraphQL API provides mutations (which are not derived from models directly) with arguments of type enum which shall accept the same values as the models only. How can I get rid of my dublication? models.py: class SomeModel(models.Model): class SomeEnum(models.TextChoices): A = "A", _("Option A") B = "B", _("Option B") enum_field = models.CharField( max_length=1, choices=SomeEnum.choices, default=SomeEnum.A, ) schema.py: class SomeEnumSchema(graphene.Enum): A = "A" B = "B" class SomeMutation(graphene.Mutation): class Arguments: some_enum = SomeEnumSchema(required=True) -
Django get all post of a parent category
I'm a begginner in django 3 and i decide to create a simple blog to pratice what i learned . I created a post model with a foreignkey category , and a model category with a self foreign key . Everething work well and i find a way to create my menu , the problem is when i click on the parent i want to have all post for the submenu . For example , I have this menu : *Informatic * Django * HTML - CSS *Graphic If i'm clicking on django , i have all my django post , same for html-css but now i want to have all informatic post , posts who have django + html-css together . I can modify my model Post and instead to have a field with category in foreign key , i could use a manytomanyfield . But i don't want it , because i can forgot to put in informatic or in other category . So what could I do, in a simple way ? Can you explain to me what and how todo , and where i need to put code I'm not sure what code do you need … -
update API request from django view
Hy guys, I'm trying to do this in a django app : my idea is simple: show a map with a marker who shows ISS's position. Every second, the marker should move because the data change. I know I can do that by calling the ISS API in Javascript but i would like to call the datas from my view with python module render. Thus, I would like to update my view without refreshing the page. My view is : def ISS(request): r =requests.get("https://api.wheretheiss.at/v1/satellites/25544").json() pos = { "latitude": r["latitude"], "longitude": r["longitude"] } return render(request, 'blog/pos_iss.html', locals()) and my template : <div id="mapid"></div> <style type="text/css"> #mapid { height: 500px; } </style> <script type="text/javascript"> const attribution = '&copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors'; const TileUrl = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'; const tiles = L.tileLayer(TileUrl, { attribution }); const lat = {{ pos|get:"latitude"|stringformat:"f" }}; //update here const long = {{ pos|get:"longitude"|stringformat:"f" }}; const mymap = L.map('mapid').setView([lat, long], 4); tiles.addTo(mymap) function getISS() { var marker = L.marker([lat, long]).addTo(mymap); } getISS(); </script> I would like the latitude and longitude to update every seconds. I think there something to do with Ajax but I don't know how. It's my first ask on stack, don't hesitate to give me a piece of … -
How to fill author or user name using python shell
I was trying to fill my author field using python shell, in shell i was typing this: Post.objects.create(title='second blog post', author="yashm", body='done via python shell') I already created a superuser named as 'yashm', but still im getting this error (see picture) Models.py file from django.db import models class Post(models.Model): title = models.CharField(max_length = 120) author = models.ForeignKey('auth.User', on_delete=models.CASCADE) body = models.TextField() def __str__(self): return self.title[:50] -
Django error in cmd while using python manage.py runserver
the error i'm getting is E:\coding\fyp\travel>python manage.py runserver Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "D:\anacondapython3\lib\threading.py", line 926, in _bootstrap_inner self.run() File "D:\anacondapython3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "D:\anacondapython3\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\anacondapython3\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "D:\anacondapython3\lib\site-packages\django\core\management\base.py", line 436, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (urls.E004) Your URL pattern [<URLResolver <URLPattern list> (admin:admin) 'admin/'>, <URLResolver <module 'app1.urls' from 'E:\\coding\\fyp\\travel\\app1\\urls.py'> (None:None) ''>, <URLPattern '^media/(?P<path>.*)$'>] is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. System check identified 1 issue (0 silenced) my settings.py: """ Django settings for travel project. Generated by 'django-admin startproject' using Django 2.2.5. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import psycopg2 # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '&d+2s#z#yxa(5vx-0+vn^(pn^115afs+csfnq0uv%w94dbth_w' # SECURITY WARNING: don't run with debug turned on in production! DEBUG … -
WinError 193 %1 is not a valid Win32 application: when deploying Django on Apache
I am on windows server 2012. I have built an API on Django rest-framework and I am trying to deploy it using WAMP and mod_wsgi. I have tested the API by running 'python manage.py runserver' and it's giving the expected output. The issue is when I am deploying it on WAMp using mod_wsgi I am able to start WAMP service but when I try to reach 'localhost' it's giving me the following error: below is the Traceback : Environment: Request Method: GET Request URL: http://localhost:8089/ Django Version: 3.0.5 Python Version: 3.7.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'API'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\core\handlers\base.py", line 100, in _get_response resolver_match = resolver.resolve(request.path_info) File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\urls\resolvers.py", line 544, in resolve for pattern in self.url_patterns: File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Administrator\Envs\predenv\Lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module return import_module(self.urlconf_name) File "c:\python376\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in … -
Integrating MediaWiki with Django
I have a Django site(say: 'xyz.com'), it contains one app as of now, however some more may be added in the future. I want to create a wiki, preferably using MediaWiki, such that it's gets displayed on 'xyz.com/wiki', and the wiki-pages like 'xyz.com/wiki/topic1' and so on. I have searched a lot for this, and I am unable to find a way to do this. The only way I can think of doing this is creating a wiki independently and then adding a redirect button on my django site. I saw a few posts suggesting to use django-wiki but I saw their demo site, and no offence, it looks hardly like a 'wiki'. I am on python 3.8.2 and django 3.0.3. Any help/suggestion is appreciated!