Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use jinja2 with django mako template tutor openedx
I'm trying to build an openedx platform with comprehensive theming. The documentation has indicated that I need to follow the same path as the original file in my theme folder. The problem is that when I try to build a new image of the openedx with my new theme I get a jinja2 template exception regarding the logout.html file. knowing that openedx requires jinja2 to work properly I need to find a workaround to this error. my logout.html file : {% extends "main_django.html" %} {% load i18n %} {% load static %} {% load django_markup %} {% block title %}{% trans "Signed Out" as tmsg %}{{ tmsg | force_escape }} | {{ block.super }} {% endblock %} {% block body %} <link rel="stylesheet" href="{% static 'css/bootstrap/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'css/partials/lms/theme/logout.css' %}"> <div class="logout-wrapper"> {% if show_tpa_logout_link %} <h1>{% trans "You have signed out." as tmsg %}{{ tmsg | force_escape }}</h1> <p style="text-align: center; margin-bottom: 20px;"> {% blocktrans trimmed asvar sso_signout_msg %} {start_anchor}Click here{end_anchor} to delete your single signed on (SSO) session. {% endblocktrans %} {% interpolate_html sso_signout_msg start_anchor='<a href="'|add:tpa_logout_url|add:'">'|safe end_anchor='</a>'|safe %} </p> {% else %} {% if enterprise_target %} {% comment %} For enterprise SSO flow we intentionally … -
javascript for loop error uncaught type error on .length
I am currently doing a school assignment. The objective is to make a simple social network posting app using Django and JavaScript. JavaScript is used in order to dynamically load posts on the web page and replace HTML parts. I was following a a YouTube lesson https://youtu.be/f1R_bykXHGE to help me. Despite the fact that I have followed the tutorial on by one I am receiving the following Uncaught TypeError: Cannot read properties of undefined (reading 'length')at XMLHttpRequest.xhr.onload ((index):63:28). const postsElement = document.getElementById("posts") // get an html element // postsElement.innerHTML = 'Loading...' // set new html in that element // var el1 = "<h1>Hi there 1</h1>" // var el2 = "<h1>Hi there 2</h1>" // var el3 = "<h1>Hi there 3</h1>" // postsElement.innerHTML = el1 + el2 + el3 const xhr = new XMLHttpRequest() const method = 'GET' // "POST" const url = "/posts" const responseType = "json" xhr.responseType = responseType xhr.open(method, url) xhr.onload = function() { const serverResponse = xhr.response const listedItems = serverResponse.response // array var finalPostStr = "" var i; for (i=0;i<listedItems.length;i++) { console.log(i) console.log(listedItems[i]) } } xhr.send() </script> -
Create a model, List should return all the movies of him, Aggregate total movies he worked (django )
My task was **Create a actor model, List should return all the movies of him, Aggregate total movies he worked Create a genre model, List should return all the movies under the genre, Aggregate total movies Create a movie model, that have name, actors and genre fields. Here actors and genre should be a manytomany relationship ** I have done this models.py from django.db import models class Actor(models.Model): actors = models.CharField(max_length=100) def __str__(self): return self.actors class Genre(models.Model): genre = models.CharField(max_length=100) def __str__(self): return self.genre class Movie(models.Model): name = models.CharField(max_length=100) actors = models.ManyToManyField(Actor) genre = models.ManyToManyField(Genre) def __str__(self): return self.name serializer.py from rest_framework import serializers from .models import Movie,Genre,Actor class ActorSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Actor fields = ['url','actors'] class GenreSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Genre fields = ['genre'] class MovieSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Movie fields = ['url','name','actors','genre'] views.py from django.shortcuts import render from rest_framework import viewsets # Create your views here. from .serializers import MovieSerializer,ActorSerializer,GenreSerializer from .models import Movie,Actor,Genre from django.db.models import Count class movie(viewsets.ModelViewSet): queryset = Movie.objects.all() serializer_class = MovieSerializer class actor(viewsets.ModelViewSet): queryset = Actor.objects.all() serializer_class = ActorSerializer class genre(viewsets.ModelViewSet): queryset = Genre.objects.all() serializer_class=GenreSerializer urls.py from django.urls import include, path from rest_framework import routers from .views import * … -
Using external input for a Django rest framework serializer
I have a class with a US cent value. When I serialize it I want to be able to convert it to a dynamically specified other currency. So the class looks like this: class Evaluation(models.Model): sum_in_cents = models.IntegerField() def converted_sum_in_cents(currency_code): currency_code = currency_code.upper() CurrencyConverter().convert(self.sum_in_cents / 100, 'USD', currency_code) ... #other stuff And it has a standard serializer that currently ignores that function: class EvaluationSerializer(serializers.ModelSerializer): class Meta: model = Evaluation fields = '__all__' depth = 1 So how, when using the serializer, should I get the currency_code argument to the converted_sum_in_cents method? (it's passed as a query string in the view) I've tried looking at read_only fields, and to_representation but as far as I can understand they seem to cover only 0-argument function calls. I've also found this thread, which is my fallback plan, but both that thread's author and I are suspicious that if that were the right way of doing something that seems like it must come up a lot, DRF would have included a lot less hacky pathway to doing it. So am I just thinking about this wrong? -
DRF return Response(serializer.data) taking more then 30 seconds to response
This is my view, I have debugged it, and getting query data and serialization takes less time but when I am doing serializer.data it takes almost 30 seconds. I have around 1000 records, and the serializer is very much nested if request.GET.get('venue') and request.GET.get('day'): venue_menu = Q(venue__name=request.GET.get('venue').title()) venue_day = Q(days__name=request.GET.get('day').title()) venue_menu_list = VenueMenu.objects.filter(venue_menu & venue_day) serializer = VenueMenuSerializer(venue_menu_list, many=True) return Response(serializer.data) else: return Response(status.HTTP_404_NOT_FOUND) -
Post, in_memory images files to external API on POST Request
Here is the scenario of this post..... A user will post some images to REST API, I have to get those images and post them to an external API to get scores calculated from an AI Modal. I have found many solutions to post the stored images to an external API, But could not find anything related to in-memory objects, SO I am posting my Solution over here so that it will be easier for someone else next time import requests from rest_framework.exceptions import ValidationError def external_api(img): api_endpoint = 'YOUR_EXTERNAL_API' payload = {} files = [ ('img', (img.get("img").name, img.get('img').file, img.get("img").content_type)) ] headers = {} response = requests.request("POST", api_endpoint, headers=headers, data=payload, files=files) return response #Serializer class ScoreCardSerializer(serializers.ModelSerializer): score_data = serializers.JSONField(read_only=True, required=False) class Meta: model = ScoreCard exclude = ['card_display'] def create(self, validated_data): score_image = validated_data.pop('score_card_image') ai_response = [] for image in score_image: ai = external_api(image) if ai.status_code == 200: ai_response.append(ai.json()) else: raise ValidationError("Server is overloaded. Please try again in few minutes") specie = ScoreCard.objects.create(**validated_data) for image in score_image: Images.objects.create(score_card_id=specie.id, img=image['img']) specie.score_data = ai_response specie.save() return specie -
Postman - Forbidden (CSRF token missing or incorrect.)
Ive been having problems getting started with postman - I've used it before with Spring but its my first time with Django. I have a working website with all URLs working well. When I send a post request in postman to a page that has a csrftoken, I can see the token in the cookies section of the results, but I get the following error in the server output: Forbidden (CSRF token missing or incorrect.): /contact/ I have the token in the headers section I have tried quite a few different solutions from stack overflow such as adding: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', ... CSRF_COOKIE_SECURE=False#I am over the localhost with http REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), This is what the view looks like def contact(request): """Renders the contact page.""" assert isinstance(request, HttpRequest) if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): ... sending email ... return redirect('contact') return HttpResponse(status=303) return render( request, 'app/contact.html', { 'title':'Contact Us', 'year':datetime.now().year, 'form': form, } ) -
Postgresql long data
I saved on my database postgresql datas example of one column : Column A ---------- a;b;c;d;e;f;g;h;i;j;k;l;m I want to separate this data where there is ";" and different columns like : Column1 Column2 Column3 Column4 ------- ------- ------- ------- a b c d How i can do it please ? -
Serializing custom count field in DRF
I am trying to send a serialized custom field that has that count of all items in a category in a vessel; I am trying to understand why this line works: vessel_inventory_category_count = serializers.IntegerField( source='vessel_inventory_category.count', read_only=True ) but this doesnt : vessel_inventory_item_count = serializers.IntegerField( source='category_items.count', read_only=True ) serializer.py : class VesselInfoSerializer(serializers.ModelSerializer): vessel_component_count = serializers.IntegerField( source='vessel_components.count', read_only=True ) vessel_inventory_category_count = serializers.IntegerField( source='vessel_inventory_category.count', read_only=True ) vessel_inventory_item_count = serializers.IntegerField( source='category_items.count', read_only=True ) class Meta: model = Vessel fields = '__all__' models.py class Category(models.Model): name = models.CharField(max_length=150, null=True, blank=True) vessel = models.ForeignKey( Vessel, blank=True, null=True, on_delete=models.CASCADE, related_name='vessel_inventory_category') def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length=150, null=True, blank=True) category = models.ForeignKey( Category, blank=True, null=True, on_delete=models.CASCADE, related_name='category_items') def __str__(self): return self.name -
How to render context when we open template from S3buckets?
I'm trying to render context in template. But I'm unable to do that. I'm opening my template from bucket and reading. Now how to render context. render_param.update({'name': email.split("@")[0],'email': email}) # html_message = loader.render_to_string(obj.html_template.url, request_data) html_message = default_storage.open(obj.html_template.name, 'r') html_message= f""" {html_message.read()} """ message = EmailMultiAlternatives(subject, html_message, email_host.email, [email]) message.attach_alternative(html_message, 'text/html') messages.append(message) -
How to autopopulate a field in models.py
I have a class named Property with a field property_type, i wana autofill this field when i create one of the other models who have onetoone relationship with Property I want the when i create a Apartment in django admin for exp the property_type in Property should autofill with the "Apartment", when i create Villa in django admin it should autofill with "villa" class Property(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="agent_of_property") district_id = models.ForeignKey(District, on_delete=models.CASCADE) slug = models.SlugField(max_length=255, unique=True) property_type = models.CharField(choices=PROPERTY_TYPE, max_length=20) title = models.TextField(verbose_name="Titulli", help_text="Vendos titullin e njoftimit", max_length=500) description = models.TextField(verbose_name="Pershkrimi", help_text="Vendos pershkrimin",max_length=1000) address_line = models.CharField(verbose_name="Adresa", help_text="E nevojeshme",max_length=255) price = models.IntegerField() area = models.IntegerField() views = models.IntegerField(default=0) documents = models.CharField(verbose_name="Dokumentacioni", help_text="Dokumentat", max_length=255) status = models.BooleanField(default=True) activity = models.CharField(max_length=20, choices=ACTION_OPTION) is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = "Prona" verbose_name_plural = "Pronat" def get_absolute_url(self): return reverse("pronat:property_detail", args=[self.slug]) def __str__(self): return self.title class Apartment(Property): property_id = models.OneToOneField(Property, on_delete=models.CASCADE, parent_link=True, primary_key=True) floor = models.IntegerField(default=0) room_num = models.IntegerField(default=0) bath_num = models.IntegerField(default=0) balcony_num = models.IntegerField(default=0) class Meta: verbose_name = "Apartament" verbose_name_plural = "Apartamentet" def save(self, *args, **kwargs): self.property_type = "Apartment" class Villa(Property): property_id = models.OneToOneField(Property, on_delete=models.CASCADE, parent_link=True, primary_key=True) living_room = models.IntegerField(default=1) floors = models.IntegerField(default=1) room_num = models.IntegerField(default=1) … -
django admin panel is locked after pushing in github repository
i was working on project in react and django and i push it into the github repository. When i pushed it into the github i got an email saying " your django secret key is leaked" . After that all my django database are not working and when i try to login to django admin panel it says "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive." I have created other superuser and tried to login but again it doesnot work. I can't find what the problem is maybe somethig went wrong after i pushed the project into the github.please help me to find the problem -
How can I create a react flow page in current django project?
In current I have a django project, it runs typically with html templates. Now I want to add react-flow pages to current project. Example: using standat url: http://127.0.0.1:8000/ops/main/ it is a normal html page with bootstrap navigation. and I want to add new page as http://127.0.0.1:8000/ops/react/xyz_flow to show react flow. and it shouldn't affect the other pages. -
How to Get Count OR Single dot on notification icon when notification comes in Django
I have created notifications API using django-notifications. and notifications successfully send using nofiy.send. But Now, I wish to add count OR dot on this Notification icon. for this 3 icons I have created separate icon.html file and calling it in every html page. and notifications getting on another notifications.html file Here is the icon.html {% if request.session.is_staff %} <div class="col"> <a href="{% url 'my-account' %}"> <h4> <span class="fas fa-user-tie"></span></h4> </a> </div> <div class="col"> <a href="{% url 'notifications' %}"> <h4><span class="fas fa-bell"></span></h4> </a> </div> <div class="col"> <div class="dropdown p-10"> <a id="dropdownMenuButton1" style="cursor: pointer;" data-bs-toggle="dropdown" aria-expanded="false"> <h4><span class="fa fa-envelope"></span></h4> </a> <ul class="dropdown-menu m-10" aria-labelledby="dropdownMenuButton1" style="margin:2px !important"> <li> <a class="dropdown-item" href="{% url 'email-logs' %}" style="padding: 5px !important;"> &nbsp;&nbsp;Email Logs </a> </li> <li> <a class="dropdown-item " href="{% url 'sms-logs' %}" style="padding: 5px !important;"> &nbsp;&nbsp;SMS Logs </a> </li> </ul> </div> </div> {% else %} <div class="col" align="right"> <a href="{% url 'my-account' %}"> <h4> <span class="fas fa-user-tie"></span></h4> </a> </div> <div class="col" align="right" style="padding-right:30px !important"> <a href="{% url 'notifications' %}"> <h4><span class="fas fa-bell"></span></h4> </a> </div> {% endif %} Notifications are getting on notifications.html. here is notifications.html {% for notification in notifications %} <div class="row"> <div class="col-12"> <div class="card"> <div class="card-body p-2"> <div class="row device"> <div class="col-1"> <h3 … -
Trying to save time input into mysql database using django
i am trying to save data from HTML input into MySql database using Django. Other forms that i created work. My conclusion is that it doesn't work because of time input. I have it converted into datettime python type which should make it work but it still doesn't save. Would you please check my code and see what can be possible the reason for it not saving? views.py file: def employee_view(request): table = employeeModel.objects.all() context = {"table": table} if request.method == "POST": postCopy = request.POST.copy() # to make it mutable postCopy['barberStartTime'] = datetime.strptime('15/05/22 ' + postCopy['barberStartTime'], '%d/%m/%y %H:%M').time() postCopy['barberEndTime'] = datetime.strptime('15/05/22 ' + postCopy['barberEndTime'], '%d/%m/%y %H:%M').time() request.POST = postCopy form = employeeForm(request.POST or NONE) if form.is_valid(): form.save() return render(request, 'accounts/employee.html', context) return render(request, 'accounts/employee.html', context) python employeeModel: class employeeModel(models.Model): barberName = models.CharField(max_length=50) barber_workplace = models.ForeignKey(workplacesModel, on_delete=models.CASCADE) barberStartTime = models.TimeField() barberEndTime = models.TimeField() class barbers: db_table = "home_employeemodel" python employeeForm: class employeeForm(forms.ModelForm): barberStartTime = forms.TimeField(widget=forms.TimeInput(format='%H:%M:%S')) barberEndTime = forms.TimeField(widget=forms.TimeInput(format='%H:%M:%S')) class Meta: model = employeeModel fields = ["barberName", "barber_workplace", "barberStartTime", "barberEndTime"] html input form: (it is part of a table - reason for tr/td tags): <tr> <form method="POST">{% csrf_token %} <td class="id-td" scope="row">---</td> <td class="barberName-td"><input type="text" name="barberName" placeholder="Meno"/></td> <td class="barberWorkplace-td"><input type="number" name="barberWorkplace" placeholder="Mesto"/></td> … -
Error ElasticBeanstalk 100.0 % of the requests are erroring with HTTP 4xx
I created a SSL Certificate and put it in Elasticbeanstalk LoadBalancer Note: Even although I add my SSL Certificate when I enter my domain there's no file in the site, it is like my aplication is not being linked to my domain Note: in Certificate Manager my Certificate status is "ok" When I deploy my application I get: 100.0 % of the requests are erroring with HTTP 4xx. Insufficient request rate (6.0 requests/min) to determine application health. ELB processes are not healthy on all instances. ELB health is failing or not available for all instances. EB Logs Resume: 172.31.38.25 - - [16/May/2022:07:18:45 +0000] "GET / HTTP/1.1" 400 58062 "-" "ELB-HealthChecker/2.0" "-" 172.31.25.200 - - [16/May/2022:07:18:52 +0000] "GET / HTTP/1.1" 400 58064 "-" "ELB-HealthChecker/2.0" "-" 172.31.38.25 - - [16/May/2022:07:19:00 +0000] "GET / HTTP/1.1" 400 58062 "-" "ELB-HealthChecker/2.0" "-" 172.31.25.200 - - [16/May/2022:07:19:07 +0000] "GET / HTTP/1.1" 400 58064 "-" "ELB-HealthChecker/2.0" "-" -
can't access ojects from dict field in mongoengine as i wants to compare and fetch data from dict filed
def recorded_meal(request ): try : schema = { "meal_plan_id": {'type': 'string', 'required': True, 'empty': False}, "id": {'type': 'string', 'required': True, 'empty': False} } v = Validator() # validate the request if not v.validate(request.data, schema): return Response({'error': v.errors}, status=status.HTTP_400_BAD_REQUEST) meal_plan_id = request.data['meal_plan_id'] id = request.data['id'] consumed_meal = MealPlan.objects(id=meal_plan_id).first() if consumed_meal: clr1 = MealPlan.recipes consumed_meal1 = clr1(id = id ).first() if consumed_meal1: serializer = serializers.MealsPlanInfoSerializer(consumed_meal1, many=False) response = serializer.data print(response) return Response({'data': response}, status=status.HTTP_200_OK) else: return Response({'error': Messages.INVALID_MEAL_ID}, status=status.HTTP_200_OK) except Exception as exception: Logger.objects.create( error=str({'error': 'Something went wrong at Learn', 'response': str(exception)}), path=str('v1/user/learn/detail') ) return Response({'error': str(exception)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR) COLLECTION of meal_plan { "_id": { "$oid": "6281e3f868715b78ac782ccd" }, "type": "standard", "round": 1, "week": 1, "day": 1, "recipes": { "breakfast": { "serves": 1, "id": "6281e4c868715b78ac782cce", "image": "Screen-shot-2012-11-30-at-10.08.27-PM11-250x250.png", "title": "Asparagus Egg Bake", "calories": 88 }, "snack": { "title": "Pea and Avocado Dip with Pita Crisps", "calories": 88, "id": "6281e4ed68715b78ac782ccf", "image": "Pea_Avo_Dip_Pita_Crisps_009_MC_LR-250x250.jpg", "serves": 1 }, "lunch": { "serves": 1, "id": "6281e50668715b78ac782cd0", "image": "Zucchini-and-Feta-Slice1-250x250.jpg", "title": "Everything but the Bagel Chicken", "calories": 88 }, "vegan": { "title": "Cleansing Grapefruit & Mint Salad", "calories": 148, "id": "6281e52d68715b78ac782cd1", "image": "Cleansing-Grapefruit-and-Mint-Salad-LR-8999-250x250.jpg", "serves": 1 }, "dinner": { "serves": 1, "id": "6281e53e68715b78ac782cd2", "image": "Screen-Shot-2014-05-30-at-1.42.47-pm-250x250.png", "title": "Roasted Red Bell Pepper and Shrimp", "calories": 88 … -
django-tables2 package show cached data
I have this installed package: django-tables2==2.4.1 The table shows some deleted objects as if the information is cached. views.py: class CustomListView(LoginRequiredMixin, PermissionRequiredMixin, SingleTableView, FilterView, CustomBaseView): def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context.update({ 'table': self.table_class(self.queryset), }) return context list.html: {% load render_table from django_tables2 %} ... <div class="card-body custom-card-body"> <div class="table-responsive"> {% render_table table %} </div> </div> Anybody could help me please? Thanks in advance. -
Is rolling out Django on WSL a valid option?
I am currently facing the challenge to rollout a Django/MySQL application on a windows computer without internet access. Though rolling out django on windows is possible, having a linux environment would be preferrable, since some mechanisms we would like to use do not run on windows. Sadly, a linux server is not an option for our customer. The question, that came to my mind now is: Would it be possible to host the django application on WSL? I have seen many topics about using wsl for django development. But i wonder if it would be a stable, secure and maintainable option for a django app in production. Do you have any experience with this setup? Are there any show stoppers I am missing? What would your recommendation be regarding django rollouts on windows? Thank you for your input. -
Set MYSQL date format from YYYY-MM-DD to DD/MM/YYYY - Django
I have a Django App with a MYSQL database and wanted to check is it possible to change the date format in MYSQL to accept dates input as DD-MM-YYYY rather than YYYY-MM-DD? I can change the date fine in Django but when I go to save my form data I currently get a date validation error stating that the date must be yyyy-mm-dd. (['“24/05/2022” value has an invalid date format. It must be in YYYY-MM-DD format.']) It works fine if I change the date to the format it wants YYYY-MM-DD but I would like the output to be DD-MM-YYYY. I read a few comment and suggestions saying to alter the settings.py file to allow different date formats (as below) but this did not seem to work either. # Date formats DATE_INPUT_FORMATS = ('%d/%m/%Y') # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-AU' TIME_ZONE = 'Australia/Melbourne' USE_I18N = True USE_L10N = True USE_TZ = True Appreciate any help anyone can offer on this. -
Django Celery Periodic task is not running on given crontab
I am using the below packages. celery==5.1.2 Django==3.1 I have 2 periodic celery tasks, in which I want the first task to run every 15 mins and the second to run every 20 mins. But the problem is that the first task is running on time, while the second is running on random timing. Although I'm getting a message on console on time for both tasks: Scheduler: Sending due task <task_name> (<task_name>) Please find the following files, celery.py from celery import Celery, Task app = Celery('settings') ... class PeriodicTask(Task): @classmethod def on_bound(cls, app): app.conf.beat_schedule[cls.name] = { "schedule": cls.run_every, "task": cls.name, "args": cls.args if hasattr(cls, "args") else (), "kwargs": cls.kwargs if hasattr(cls, "kwargs") else {}, "options": cls.options if hasattr(cls, "options") else {} } tasks.py from celery.schedules import crontab from settings.celery import app, PeriodicTask ... @app.task( base=PeriodicTask, run_every=crontab(minute='*/15'), name='task1', options={'queue': 'queue_name'} ) def task1(): logger.info("task1 called") @app.task( base=PeriodicTask, run_every=crontab(minute='*/20'), name='task2' ) def task2(): logger.info("task2 called") Please help me to find the bug here. Thanks! -
[FreeTDS][SQL Server]SQL Anywhere Error -265: Procedure 'SERVERPROPERTY' not found
I'm trying to connect to sybase database with pyodbc. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'mssql_database': { 'ENGINE': 'django_pyodbc', 'NAME': 'blabla', 'USER': 'blabla', 'PASSWORD': 'blabla', 'HOST': '10.65.1.20', 'PORT': '1433', 'OPTIONS': { 'driver': 'FreeTDS', 'host_is_server': True, }, }, 'sybase_database': { 'ENGINE': 'django_pyodbc', 'NAME': 'blabla', 'USER': 'blabla', 'PASSWORD': 'blabla', 'HOST': '10.60.1.6', 'PORT': '2638', 'OPTIONS': { 'driver': 'FreeTDS', 'host_is_server': True, }, }, } Connection to mssql_database works. But connection to sybase_database ends with this error message: django.db.utils.DatabaseError: ('42000', "[42000] [FreeTDS][SQL Server]SQL Anywhere Error -265: Procedure 'SERVERPROPERTY' not found (504) (SQLExecDirectW)") $ pip list Package Version ------------- ------- Django 1.8 django-pyodbc 1.1.3 pip 21.3.1 pyodbc 4.0.32 setuptools 59.6.0 sqlany-django 1.13 sqlanydb 1.0.11 wheel 0.37.1 -
djang many to many relationship with self referencing
How can I do a many to many relationship in django with the same class but disable the possibility to do a relationship with the same Person. Like a boss can have a relationship with many persons but shouldn't be possible to do a relationship with him self, but they are in the same class. -
Django Ajax pass data with primary key to view
Help been trying to pass data between views using ajax and a primary key. Example a view and a detailView of object in my database. I am able to Get & Post data. Below is my Js Code. Thanks. // CSRF TOKEN // function getCookie(name) { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } const csrftoken = getCookie('csrftoken'); // Create // var form = document.getElementById('form-wrapper') form.addEventListener('submit', function(e){ e.preventDefault() console.log('Nimetuma') var url = 'http://127.0.0.1:8000/swimmers-create/' var title = document.getElementById('tester').value var date = document.getElementById('date-time').value fetch(url, { method:'POST', headers: { 'Content-type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'sessions':title,'date_from':date}) }).then(function(response){ apiList() document.getElementById('form-wrapper').reset() }) }); // More Details // Thank you all for the help and support much appreciated. -
Adaptive Server is unavailable or does not exist
I'm trying to connect to mssql server via FreeTDS. First I tried it via ODBC Driver 17 for SQL Server and it works. Here is my configuration in settings.py. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'mssql_database': { 'ENGINE': 'django_pyodbc', 'NAME': 'blabla', 'USER': 'blabla', 'PASSWORD': 'blabla', 'HOST': '10.65.1.20', 'PORT': '', 'OPTIONS': { 'driver': 'ODBC Driver 17 for SQL Server', }, }, } According to this guide I installed FreeTDS on Ubuntu 18.04. Here is my /etc/odbcinst.ini [ODBC Driver 17 for SQL Server] Description=Microsoft ODBC Driver 17 for SQL Server Driver=/opt/microsoft/msodbcsql17/lib64/libmsodbcsql-17.9.so.1.1 UsageCount=1 [FreeTDS] Description = TDS driver (Sybase/MS SQL) Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so CPTimeout = CPReuse = And here is the new settings.py section DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'mssql_database': { 'ENGINE': 'django_pyodbc', 'NAME': 'blabla', 'USER': 'blabla', 'PASSWORD': 'blabla', 'HOST': '10.65.1.20', 'PORT': '', 'OPTIONS': { 'driver': 'FreeTDS', 'host_is_server': True, 'extra_params': "TDS_VERSION=8.0" }, }, } And I have this error message pyodbc.OperationalError: ('08S01', '[08S01] [FreeTDS][SQL Server]Unable to connect: Adaptive Server is unavailable or does not exist (20009) (SQLDriverConnect)') How can I fix the error? The connection works with ODBC Driver 17 for SQL Server. So why doesn't it work with …