Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django bootstrap form and button is displaying on browser output extra large
this is my link: <a href="#" class="btn btn-danger">link</a> in the browser it looks too big with djnago but when this link I aplly without django then it's size works well what should i do -
Django not loading static css files
In the process of conntec to a space on digital ocean, I ran python manage.py collectstatic For {% static 'image/image_name.jpg %} works, my images show up, bu for <link rel="stylesheet" type="text/css" href="{% static 'css/fontawesome/css/all.css' %}"> my font awesome isn't showing up. I've checked the location of this link, and I am getting back the correct location, but I don't know what is causing the issue. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = os.path.join(BASE_DIR, 'static'), # https://unlock-optimal-performance.nyc3.digitaloceanspaces.com STATIC_ROOT = os.path.join(BASE_DIR,"staticfiles-cdn") # in production we want cdn MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles-cdn', 'uploads') from .cdn.conf import AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_STORAGE_BUCKET_NAME,AWS_S3_ENDPOINT_URL,AWS_S3_OBJECT_PARAMETERS,AWS_LOCATION,DEFAULT_FILE_STORAGE,STATICFILES_STORAGE urls.py urlpatterns += staticfiles_urlpatterns() Any reason why my images are showing up but not my css ? -
AttributeError at 'WSGIRequest' object has no attribute 'Post'
When i click vote button I got this error AttributeError at /polls/2/vote/ 'WSGIRequest' object has no attribute 'Post'. When i tried to vote for any poll. This is my results.html file I am using django==3.2 and python 3.8 <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label> <br> {% endfor %} </fieldset> <input type="submit" value="Vote" > </form> -
Django - importing from subordinary folder
I'm making django blog app. And i have problem with import .py file from subordinate directory. Does anyone has any advice maybe what is wrong here? enter image description here -
Redirect back to original post after updateview
I have an update view that is working as expected. The only issue is that I cant figure out how to redirect back to the post that was being updated. I believe I am on the right track with get_success_url but I cant get it working view class UpdateBuildLog(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = BuildLog form_class = BuildLogupdateForm template = 'blog/buildlog_update.html' def get_object(self): return BuildLog.objects.get(pk=self.kwargs["pkz"]) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_success_url(self): pk = self.kwargs["pkz"] return reverse("build-log-view", kwargs={"pkz": pk}) def test_func(self): post = self.get_object() if self.request.user.id == post.author_id: return True return False urls: path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'), path('post/<int:pk>/build-log/<int:pkz>/delete/', views.BuildLogDelete, name='build-log-delete'), path('post/<int:pk>/build-log/<int:pkz>/update/', UpdateBuildLog.as_view(), name='build-log-update'), -
Django model generates hundreds of files in a saving loop
I'm using Django 3.8.2 on Ubuntu 18.04, I'm generating a PDF file upon saving a django model but files are generated in a loop endlessly. I have this django model: class Fattura(models.Model): ordine = models.ForeignKey(Ordine, on_delete=models.CASCADE, related_name="fatture", null=False) pdf = models.FileField(upload_to='archivio/fatture/%Y/%m') the pdf field is generated when an instance is saved, based on the information contained in the related "ordine" field which is a ForeignKey to this other model: class Ordine(models.Model): utente = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ordini", null=False) data = models.DateField(auto_now_add=True) abbonamento = models.ForeignKey(Abbonamento, on_delete=models.PROTECT, null=False) importo = models.DecimalField(max_digits = 5, decimal_places = 2, null=False) I declared every instructions for the generation of the PDF inside the save() method of my Fattura model. I'm using the library that is recommended by Django's documentation: reportlab. Here is the custom save method: def save(self, *args, **kwargs): self.count_save += 1 # I defined this attribute which I increment to understand what is actually looping print("COUNT SAVE: " + str(self.count_save)) # it always grows, that's the save method being re-called if self.pdf._file == None: try: buffer = io.BytesIO() p = canvas.Canvas(buffer) p.drawString(100,100, str(self.ordine)) p.showPage() p.save() buffer.seek(0) utente = self.ordine.utente num_questa_fattura = utente.ordini.count() nome_file = "{}_{}-{}.pdf".format( self.ordine.utente.first_name.lower(), self.ordine.utente.last_name.lower(), num_questa_fattura) percorso = '{}/upload/archivio/fatture/{}/{}/{}'.format( BASE_DIR, # from settings.py … -
Django Python Creating Object inside Model delete function returns 500 Error
I am trying to create a new Entry of CloudProfileTransaction before deleting a record. When saving a new record the exact same code works fine ( with: super().save(*args, **kwargs)). If I remove the CloudProfileTransaction code the deletion works. the following code throws a Response 500 Error. what am I missing? def delete(self, *args, **kwargs): CloudProfileTransaction.objects.create( cloud_giver = self.follower, cloud_receiver = self.followee, cloud_model = CloudModel.objects.get(investment='Follow'), add = False ) Followers.objects.filter(user=self.follower).update(followers=F('followers')-1) Followees.objects.filter(user=self.followee).update(followees=F('followees')-1) super().delete(*args, **kwargs) Error Message: E/Volley: [28490] NetworkUtility.shouldRetryException: Unexpected response code 500 -
How to display all fields, including related ones, in a Django Serializer using abbreviated syntax?
I know I can use this syntax for all fields: class EventSerializer(serializers.ModelSerializer): class Meta: model = models.Event fields = '__all__' class GuestList(LogicalDeleteModel): events = models.ManyToManyField(Event, through='EventGuestList', through_fields=('guest_list', 'event'), related_name='guest_list') But this does NOT include any of the related fields. In this example, I want guest_list to also be a part of the serializer. I know that I can simply declare all the fields explicitly, including the related ones, but I was wondering if there's any chance I could avoid it. -
How to count number of student in a school in Django?
class School(models.Model): name = models.CharField() city = models.CharField() street = models.CharField() class Student(models.Model): school_id = models.ForeignKey(School, on_delete=models.CASCADE) first_name = models.CharField() last_name = models.CharField() I want to join two classes School and Student and get the number of students in these school, So I wrote this code in my serializers. but I got no resulte of number of students, only the two classes joined. Can someone help me? serializers.py from django.db.models import Count class SchoolSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = School fields = ['name'] class StudentSerializer(serializers.HyperlinkedModelSerializer): school = SchoolSerializer() school.objects.annotate(num_of_students=Count('student')) class Meta: model = Student fields = ['first_name', 'last_name', 'school'] views.py In my views I wrote the following code: class StudentViewSet(viewsets.ModelViewSet): serializer_class = StudentSerializer queryset = Student.objects.all() -
django.db.utils.OperationalError: no such table: MainApp_user when i try to create superuser
I make some web application, and almost in the end of development process i decided to customize user model to make profile page with many other info. Recently i have found a video where example from django docs is explained, and i made the same code as there was, but at first i delete my file db.sqlite3 and now when i try to create a superuser i do always catch the next error: django.db.utils.OperationalError: no such table: MainApp_user Here is my models.py: class MyUserManager(BaseUserManager): def create_user(self, username, password): if not username: raise ValueError("Mailname field is empty") if not password: raise ValueError("You have to set password") user = self.model( username=username, ) user.set_password(password) user.save(using=self._db) return user class User(AbstractBaseUser): username = models.CharField(max_length=30, unique=True) password = models.CharField(max_length=64) name = models.CharField(max_length=30, blank=True) surname = models.CharField(max_length=30, blank=True) avatar = models.ImageField(width_field=512, height_field=512) email_link = models.CharField(max_length=64, blank=True, null=True) bio = models.CharField(max_length=512, blank=True, null=True) registered = models.DateField(auto_now_add=True) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['password'] objects = MyUserManager() def __str__(self): return self.username Also i've added the next variable in settings.py: AUTH_USER_MODEL = "MainApp.User" Why this error happens and how to solve it, help please. ***Ofc, i did made migrations to database -
How to use an outside script within a Django Project?
Sorry for the wording on the question if it isn't clear. I am rather new to Django but not too new to Python. I have a Model in my Django Project, which keeps track of trailer locations. I then need to use another script to update this data. However, when running this script, the Dict that is suppose to be returned is not getting returned properly. class TrailerLocation(models.Model): trailer = models.OneToOneField(Trailer, on_delete=models.CASCADE) locationCity = models.CharField(max_length=70, null=True, blank=True) locationState = models.CharField(max_length=30, null=True, blank=True) locationCountry = models.CharField(max_length=50, null=True, blank=True) locationStatus = models.CharField(max_length=200, null=True, blank=True) latitude = models.CharField(max_length=200, null=True, blank=True) longitude = models.CharField(max_length=200, null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) # def __str__(self): # return self.trailer def createLocation(self, trailer): trailerLocation = TrailerLocation(trailer=trailer) trailerLocation.save() def getLocations(self): locDataDict = trailerLocations.run() print(locDataDict) for key in locDataDict.keys(): datalist = locDataDict[key] self.updateLocation(key, datalist) -
Django - How to populate choices in a modelchoicefield with a field from another model filtered by logged in user
I'm trying to made a modelform with a modelchoicewidget which inherits its choices from another model than the model the modelform is connected to, and this selection is to be filtered by the current logged in user. The example below illustrates my intentions - let's say I have two different models where one model allows the user to register meal types (breakfast, dinner etc), and the other model allows the user to create specific meals based on those meal types, with the connecting variable being the title of the meal type. models.py: class Mealtypes(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200, default='') description = models.TextField(default='') class Specificmeals(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) meal_name = models.CharField(max_length=200, default='') mealtype = models.CharField(max_length=200, default='') fruit = models.BooleanField(default=False) meat = models.BooleanField(default=False) dairy = models.BooleanField(default=False) forms.py from django import forms from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Mealtypes, Specificmeals class MealAdder(ModelForm): class Meta: model = Specificmeals fields = [ 'meal_name', 'mealtype', 'fruit', 'meat', 'dairy', ] widgets = { 'text': forms.Textarea(attrs={"style": "height:10em;" "width:60em;"}), 'mealtype': forms.ModelChoiceField(queryset=Mealtypes.title.filter(author='author')), 'fruit': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}), 'meat': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}), 'dairy': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}), } I'm trying to play around with the ModelChoiceField to make it query the mealtypes from the Mealtypes model filtered … -
Read from file output to html template in django
How would the solution linked below be written in views.py to read from multiple files and output those various fields? I can make this work for one but if I try copy pasting f = open('path/text.txt', 'r') file_content = f.read() f.close() context = {'file_content': file_content} and changing the letters slightly to have unique versions it seems to break it...I am passing in unique variations not reusing "f" ex: h = open(BASE_DIR, 'path/tofile') file_content = h.read() h.close() context = {'file_contenth': file_contenth} I then pass in to the return return render(request, pathtohtml, {'file_content': file_content}, {'file_contenth': file_contenth} and that "breaks" it. I've tried a few variations of passing those variables in to no avail I used the solution found here Django: Display contents of txt file on the website -
Reverse for 'extranet.views.uutiset_paasivu' not found. 'extranet.views.uutiset_paasivu' is not a valid view function or pattern name
I'm trying update django project from django1.4/python 2.7 to django2.2/python3.7. Now I'm confused with the traceback after pythan manage.py runserver (and after going to page /uutiset/): Internal Server Error: /search/ Traceback (most recent call last): File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\miettinj\osakeekstra\extranet\views.py", line 78, in search { 'query_string': query_string, 'dokut': found_entries }) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 163, in _render return self.nodelist.render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\template\defaulttags.py", line 443, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\urls\base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\miettinj\verkko\venv\lib\site-packages\django\urls\resolvers.py", line 660, in … -
django authentication with ldap3
I am testing django_python3_ldap library and using the same ldap server that I found in the tutorial (https://ldap3.readthedocs.io/en/latest/tutorial_intro.html), but there is something which I didn't get right to stablish the connection. Does anyone know what is wrong with these settings configuration? This is the error: "LDAP bind failed: LDAPInvalidCredentialsResult - 49 - invalidCredentials - None - None - bindResponse - None" This is my code in settings.py: AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "django_python3_ldap.auth.LDAPBackend", ] # The URL of the LDAP server. LDAP_AUTH_URL = "ldap://ipa.demo1.freeipa.org" # Initiate TLS on connection. LDAP_AUTH_USE_TLS = False # The LDAP search base for looking up users. LDAP_AUTH_SEARCH_BASE = "uid=admin,cn=users,cn=accounts,dc=demo1,dc=freeipa,dc=org" #"dc=demo1,dc=freeipa,dc=org" # The LDAP class that represents a user. LDAP_AUTH_OBJECT_CLASS = "*" # User model fields mapped to the LDAP # attributes that represent them. LDAP_AUTH_USER_FIELDS = { "username": "sAMAccountName", #"username", "first_name": "givenName", "last_name": "sn", "email": "mail", } # A tuple of django model fields used to uniquely identify a user. LDAP_AUTH_USER_LOOKUP_FIELDS = ("username",) # Path to a callable that takes a dict of {model_field_name: value}, # returning a dict of clean model data. # Use this to customize how data loaded from LDAP is saved to the User model. LDAP_AUTH_CLEAN_USER_DATA = "django_python3_ldap.utils.clean_user_data" # Path to a … -
How to properly delete an instance of a model in Django
I am trying to delete an instance of an event from my calendar. I then want Django to redirect to the calendar page upon deletion of the event. In my views.py, I have defined an event_delete function: def event_delete(request, event_id=None): Event.objects.get(pk=event_id).delete() return HttpResponseRedirect(reverse("cal:calendar")) In my urls.py I have defined a url for deletion: from django.conf.urls import url from . import views app_name = "cal" urlpatterns = [ url(r"^index/$", views.index, name="index"), url(r"^calendar/$", views.CalendarView.as_view(), name="calendar"), url(r"^event/new/$", views.event, name="event_new"), url(r"^event/edit/(?P<event_id>\d+)/$", views.event, name="event_edit"), url(r"^event/delete/$", views.event_delete, name="event_delete"), ] and in my event.html, I have defined an a tag that takes in event_delete: <a class="btn cancel-button buttons login_btn" href="{% url 'cal:event_delete' %}" value="Delete" style="font-family:Optima;">Delete Event</a> When I try to delete an event, it redirects me back to the calendar page but I still see the event. If I try again, it gives me the error DoesNotExist at /event/delete/ Event matching query does not exist. When I check in my admin however, I still see the instance of the event. Please advice as to how I can resolve this. -
Django migrations not working with multiple apps
I have created a project with django which has 2 apps. Each of them has a models.py that I will show below. The problem occurs when I try to launch: python manage.py makemigratios I get the following error: Traceback (most recent call last): File "/home/pablo/.local/share/virtualenvs/portfolio-cTVCjELO/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: no existe la relación «weatherapi_weatherstation» LINE 1: ...gitude", "weatherapi_weatherstation"."token" FROM "weatherap... ... return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: no existe la relación «weatherapi_weatherstation» LINE 1: ...gitude", "weatherapi_weatherstation"."token" FROM "weatherap... ^ The above exception was the direct cause of the following exception: They are two very simple models and everything seems to be correct but it is impossible to launch makemigrations. I have also tried to drop the DB but it is still the same. Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'portfolio', 'USER': 'pablo', 'PASSWORD': '1234', 'HOST': 'localhost', 'PORT': '5432', } } Models 1: from uuid import uuid1 from django.db import models def generate_uid(): return uuid1().hex # Create your models here. class WeatherStation(models.Model): uid = models.CharField(max_length=32, db_index=True, unique=True, default=generate_uid) name = models.CharField(max_length=256, default="No name") created_at = models.DateTimeField(auto_now_add=True) latitude = models.FloatField() longitude = models.FloatField() token = models.CharField(max_length=40, unique=True,) def __str__(self): return self.name class WeatherRecord(models.Model): created_at = models.DateTimeField(auto_now_add=True) temperature … -
How to filter books by number of editions Django?
models.py class Category(models.Model): image = models.ImageField(upload_to='book_images/category_images') title = models.CharField('Назва', max_length=128) slug = models.CharField(blank=True, max_length=128) class Book(models.Model): image = models.ImageField('Зображення', blank=False, upload_to='book_images') title = models.CharField('Назва', max_length=128) price = models.DecimalField('Ціна', max_digits=6, decimal_places=2) author = models.ForeignKey(Author, on_delete=CASCADE, verbose_name='Автор') edition = models.ForeignKey(Edition, on_delete=CASCADE, verbose_name='Видавництво') category = models.ForeignKey(Category, on_delete=CASCADE, verbose_name='Категорія') I want to display top 3 editions by count of their books. How can I do that? -
failing to create app for django with visual studio
i am failing to create app for Django. i am getting this error "[Errno 2] No such file or directory". i tried the following code:python manage.py startapp cloud.I am still failing. I would appreciate any help. Regards -
django.db.utils.ProgrammingError: set_session cannot be used inside a transaction
I am trying to save objects in DB [obj.save()] with the help of ORMs. But it throws the following error: django.db.utils.ProgrammingError: set_session cannot be used inside a transaction Does any ideas about this error? I am using Django & PostgresDB -
Particular Query from Queryset in Django
I have a model in Django called Accounts which has id, name, email, and balance fields. I want to retrieve the particular dataset when one visits the detail page. Say when I click on the details page I send through a string "name" which contains the name of the user the account is owned by. I am trying to obtain the particular query but to no avail. This is what the Queryset returns on Accounts.objects.all() ==> <QuerySet [<Account: UserA>, <Account: UserB>, <Account: UserC>, <Account: UserD>, <Account: UserE>, <Account: UserF>, <Account: UserG>, <Account: UserH>, <Account: UserI>, <Account: UserJ>]> I have tried Accounts.objects.values().get(id=id) but that provides a dictionary of id, user_id, and balance. I want to access the email of the user as well. I tried Accounts.objects.get(username=name) but it returns the error too many values to unpack. A way to do is Accounts.objects.all()[id] which is cheap and not dynamic since if we delete some users then it wont work. What am I missing here? or what is going wrong here? -
Django: submit only one form created with for loop
In my code I'm using a class CreateView with a ListView. I'm also using a for loop to show all the possible dates available (that are created in the StaffDuty models). My user should be able to just book a single date. My problem is that I'm not able to save a single appointment, I have to compile all the form showed in my list to be able to submit. How can I solve this? models.py class UserAppointment(models.Model): user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) staff = models.ForeignKey(StaffDuty, on_delete=models.CASCADE) event = models.ForeignKey(Event, on_delete=models.CASCADE) event_name = models.CharField(max_length=255) date_appointment = models.DateField(null=True) def __str__(self): return self.event.name | str(self.staff.date_work) def get_absolute_url(self): return reverse('home') views.py class UserAppointmentAddView(CreateView): model = UserAppointment form_class = UserAppointmentForm template_name = "reservation.html" def form_valid(self, form): form.instance.user = self.request.user.userinformation def get_context_data(self, **kwargs): kwargs['object_list'] = StaffDuty.objects.order_by('id') return super(UserAppointmentAddView, self).get_context_data(**kwargs) html <div class="container"> <form method="post"> {% csrf_token %} {% for appointment in object_list %} <span>{{ form.staff }}</span> <span>{{ form.event }}</span> <span>{{ form.morning_hour }}</span> <span>{{ form.afternoon_hour }}</span> <div class="primary-btn"> <input type="submit" value="submit" class="btn btn-primary"> </div> </div> {% endfor %} -
How to inspect query generated by generic CreateView
I have a generic CreateView and it doesn't work as intended. In my db I have a table with composite primary key of two fields. When I try to create more then one instances of this table I get error message 'Order details with this Order already exists.'. Seems like query generated by CreateView is trying to update existing row, but I want it to create new one. It's all my assumptions and I wonder how can I check the exact query generated by Django's ORM. I suppose it's trying to update, not insert. How do I check that? Thanks. If needed, here's the view and model. class OrderDetailsCreateView(LoginRequiredMixin, CreateView): model = OrderDetails template_name = 'orders/orderdetails_create.html' form_class = OrderDetailCreateOrUpdateForm def get_form_kwargs(self, **kwargs): form_kwargs = super(OrderDetailsCreateView, self).get_form_kwargs(**kwargs) emp = get_current_users_employee(self.request.user) last_order = Orders.objects.filter(employee=emp, id=self.kwargs['pk'])[0] last_order_details = OrderDetails.objects.filter(order=last_order).values('product_id') already_selected_products = last_order_details form_kwargs['already_selected_products'] = already_selected_products form_kwargs['emp'] = emp return form_kwargs def form_valid(self, form): return super(OrderDetailsCreateView, self).form_valid(form) class OrderDetails(models.Model): order = models.OneToOneField('Orders', models.DO_NOTHING) product = models.ForeignKey('products.Products', models.DO_NOTHING) unit_price = models.FloatField() quantity = models.SmallIntegerField() discount = models.FloatField() class Meta: managed = False db_table = 'order_details' constraints = [ models.UniqueConstraint(fields=['order', 'product'], name='order-product') ] def get_absolute_url(self): return u'/orders/%d' % self.order.pk -
Running multiple django projects using docker and nginx
I am trying to do the following. I have 3 django projects (NOT apps) (can be more). Proj1: On port 8000, Proj2: 8001, and Proj3:8002 This is what I am trying to achieve: User visits : localhost:8000 All urls under Pr1: Respond User visits: localhost:8000/Pr2 All urls under Pr2: Respond User visits: localhost:8000/Pr3 All urls under Pr3: Respond Goal: Proj 1 is run with Docker and Nginx. Now I have 2 new projects to integrate. Every new sub project should be reached using only one main port (8000). But internally the request is directed towards the correct port of sub-project. Why this goal: Achieve micro-service style structure. Sub projects (2 & 3) can be reached only after authentication through Proj1. What have I tried: Honestly no clear idea where to start. Added new projects to docker-compose...they all work when visited by their own port(localhost:8001/Prj1) .. With nginx, tried adding a new server. No effect: server { listen 4445; location / { proxy_pass http://web_socket:8080; proxy_redirect off; } } -
building an e-learning web site with ontology OWL and Django
i'm actually working on a new project about creating an e-learning platform using ontologies for my final project graduation, i'm absolutely a blank page with the domain! i've started by creating my ontology with the protege editor and actually im trying to display my data on my web site programmed with the django framework which is really difficult ! i have searched about many sites and i did not found anything about owl programming with python and also django ! is there someone who can give me some kind of advice on how to build this web app using ontologies ?