Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use "HyperlinkedModelSerializer" in Django REST API?
I got an error message: HyperlinkedIdentityField requires the request in the serializer context. Add context={'request': request} when instantiating the serializer. when I'm using API to get data. What am I doing wrong here? models.py class User(AbstractUser): username = models.CharField(blank=True, null=True, max_length=255) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return "{}".format(self.email) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='profile') title = models.CharField(max_length=5) dob = models.DateField() address = models.CharField(max_length=255) country = models.CharField(max_length=50) city = models.CharField(max_length=50) zip = models.CharField(max_length=5) photo = models.ImageField(upload_to='uploads', blank=True, ) serializers.py class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('title', 'dob', 'address', 'country', 'city', 'zip', 'photo') class UserSerializer(serializers.HyperlinkedModelSerializer): profile = UserProfileSerializer(required=True) class Meta: model = User fields = ('url', 'email', 'first_name', 'last_name', 'password', 'profile') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): profile_data = validated_data.pop('profile') password = validated_data.pop('password') user = User(**validated_data) user.set_password(password) user.save() UserProfile.objects.create(user=user, **profile_data) return user def update(self, instance, validated_data): profile_data = validated_data.pop('profile') profile = instance.profile instance.email = validated_data.get('email', instance.email) instance.save() profile.title = profile_data.get('title', profile.title) profile.dob = profile_data.get('dob', profile.dob) profile.address = profile_data.get('address', profile.address) profile.country = profile_data.get('country', profile.country) profile.city = profile_data.get('city', profile.city) profile.zip = profile_data.get('zip', profile.zip) profile.photo = profile_data.get('photo', profile.photo) profile.save() return instance And views.py class UserList(ListCreateAPIView): ''' Return list all … -
How to update a field in a model by matching with different field in another model in django
i have a model called proposed with with three fields ,1st field(commodity) and 2nd field(rate) is being filled dynamically from views and third field (commodity_name) is empty.There is another model called list which contains two fields called com_id and com_name and both fields contain static data, what i want to do is match my proposed model's commodity field with my list model's com_id (they have same datatype) and update proposed models commodity name with list models com_name field which is in the same row as matched com_id.i need some ideas on how to do achieve this,any help is appreciated ,thank you. -
Django display posts on index page with few answers (linked by foreign key) under each one of them
I am writing an Imageboard in Django but I can't get over this basic issue how to display few answers to each post on the mainpage. I have two models, Thread and Answer, and answer is linked by foreign key to thread. I would like to display each Thread with three latest answers underneath. I would really appreciate some help here. -
Django migrate multiple databases issue
I am doing a project with Django, there are too much data so that I need to form different databases to store them. I made a database router for each app to match the unique database, but when I maigrate them, all the tables were migrate to the same database, here are the codes: from django.conf import settings DATABASE_MAPPING = settings.DATABASES_APPS_MAPPING class DatebaseAppsRouter(object): """ 该类为连接不同数据库的路由,在setting中通过设置DATABASE_MAPPING来匹配数据库 例: DATABASE_APPS_MAAPING = {"app1":"db1", "app2":"db2"} """ def db_for_read(self, model, **kwargs): """将所有读操作指向指定的数据库""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def db_for_write(self, model, **kwargs): """将所有写操作指向指定的数据库""" if model._meta.app_label in DATABASE_MAPPING: return DATABASE_MAPPING[model._meta.app_label] return None def allow_relation(self, obj1, obj2, **kwargs): """允许使用相同数据库的应用程序之间的任何关系""" db_obj1 = DATABASE_MAPPING.get(obj1._meta.app_label) db_obj2 = DATABASE_MAPPING.get(obj2._meta.app_label) if db_obj1 and db_obj2: if db_obj1 == db_obj2: return True else: return False else: return None def allow_syncdb(self, db, model): """确保这些应用程序只出现在相关的数据库中""" if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(model._meta.app_label) == db elif model._meta.app_label in DATABASE_MAPPING: return False return None def allow_migrate(self, db, app_label, model=None, **kwargs): """确保身份验证应用程序只出现在login数据库中""" if db in DATABASE_MAPPING.values(): return DATABASE_MAPPING.get(app_label) == db elif app_label in DATABASE_MAPPING: return False return None By using the router, I would like to migrate multiple databases, but it doesn't work System check identified some issues: WARNINGS: ?: (urls.W001) Your URL pattern '^login/$' uses include with a … -
Python: What is 'theweek' parameter in the formatweek() method in HTMLCalendar?
I am making a web app in Python/Django and I am trying to make a calendar that displays meetings using the HTMLCalendar class in the calendar module. I am overriding the formatday(), formatweek() and formatmonth() methods in HTMLCalendar. I have written my new code for the formatday() function. I have found two code samples for the formatweek() function demonstrating its usage: # Sample 1 def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) return f'<tr> {week} </tr>' # Sample 2 def formatweek(self, theweek, width): """ Returns a single week in a string (no newline). """ return ' '.join(self.formatday(d, wd, width) for (d, wd) in theweek) I am not sure what theweek parameter is exactly. I have searched online for documentation for formatweek() but I could not find anything that outlined what theweek parameter is. Any insights are appreciated. -
How to get the related images in DRF?
Here I have two models and have Many-to-one relation . In the ListPackageGallery class I want to list all the images uploaded to some package. How can I query the images of some particular package here? I am very new to django rest.So am I going the right way by using the generics API view for such cases ? class Package(models.Model): name = models.CharField(max_length=255,unique=True) slug = AutoSlugField(populate_from='name') package_desc = models.TextField() class PackageGallery(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE) image = models.ImageField(upload_to='package_gallery') serializers.py class PackageGallerySerializer(serializers.ModelSerializer): class Meta: model = PackageGallery fields = '__all__' views.py class CreatePackageGallery(generics.CreateAPIView): serializer_class = PackageGallerySerializer queryset = PackageGallery.objects.all() class ListAllGallery(generics.ListAPIView): serializer_class = PackageGallerySerializer queryset = PackageGallery.objects.all() class ListPackageGallery(generics.RetrieveAPIView): serializer_class = PackageGallerySerializer lookup_field = 'slug' def get_queryset(self): return PackageGallery.objects.filter(package=self.slug) #i got stuck here urls.py path('create/gallery/',CreatePackageGallery.as_view(),name='create_package_gallery'), path('list/all/gallery/',ListAllGallery.as_view(),name='list_all_gallery'), path('list/<slug>/gallery/',ListPackageGallery.as_view(),name='list_package_gallery'), -
Django How do i display different pages on one html
I am currently making a movie reservation site using django. The first page lists the currently screened movies. If I click on one of them, then go to the page where shows the details of the movie. If there are movie A, B, and C that is currently being screened. For example If I click A, I want to have detailed information about A movie on the movie details information page. If I click B, I want to have detailed information about B movie on the movie details information page. If I click C, I want to have detailed information about C movie on the movie details information page. I want to make it not using javascript!! only using django and html!! Could you please help me? moviehome.html / Showing Current playing movies and Coming soon movie <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Current Playing</h1> Hi, {{user}}! <a href="{% url 'signout' %}">LOG_OUT</a><br> {% for movieinfos in movie.all %} <a href="{% url 'realinfo'%}"><img src="{{movieinfos.movie_poster.url}}" width=100px height=150px></a><br> {{movieinfos.movie_age}} <a href="{% url 'realinfo'%}">{{movieinfos.movie_name}}</a><br> 장르 | {{movieinfos.movie_genre}}<br> 감독 | <a href="{% url 'directorinfo' %}">{{movieinfos.movie_director}}</a><br> 출연 | <a href="{% url 'actorinfo' %}">{{movieinfos.movie_actor1}}</a> , <a href="{% url 'actorinfo' %}">{{movieinfos.movie_actor2}}</a> <br> {% endfor … -
Django / Bootstrap 4 / Blog Post || How to get responsive images?
I've been able to add images to my post with ckeditor which is great but I can't seem to get the images to shrink and be responsive like the rest of the content/text in my post. I've tried a few tutorials and played around with things but nothing seems to work. Thanks. Here is my BASE.HTML {% load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link rel="stylesheet" type="text/css" href="{% static 'portfolio_app/main.css' %}"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Davi Silveira DoP</title> </head> <body> <main role="main"> {% if messages %} {% for message in messages %} <div class="alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} {% block content %}{% endblock %} </main> <footer class="text-muted"> <div class="container"> <p class="float-right"> <a href="#">Back to top</a> </p> <p class="text-muted">Davi Silveira &copy; 2020</p> <p>Associated with <a href="https://www.facebook.com/silveirabrothers/">Silveira Brothers Films</a></p> </div> </footer> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script> </body> </html> BLOG.HTML {% extends "portfolio_app/base.html" %} {% block content %} <div class="container"> <div class="row"> <div … -
How can i fix django rest framework metaclass conflict
i am a beginner learning django rest framework and i just encounter this error and i cant seem to find a way around it, please i need gurus to help me out. Here is the permissions.py sample code from rest_framework import permissions class UpdateOwnProfile(permissions, BaseException): """Allow user to edit their own profile""" def has_object_permission(self, request, view, obj): """Check if user is trying to update their own profile""" if request.method in permissions.SAFE_METHODS: return True return obj.id == request.user.id Here is also a sample of the views.py sample codes from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from rest_framework import viewsets from rest_framework.authentication import TokenAuthentication from profiles_api import serializers from profiles_api import models from profiles_api import permissions class HelloApiView(APIView): """Test Api view""" serializer_class = serializers.HelloSerializer def get(self, request, format=None): """Returns a list of Api features""" an_apiview = [ 'Uses HTTP methods as function (get, post, patch, put, delete)', 'Is similar to a traditional Django view', 'Gives you the most control over your application logic', 'Is mapped manually to URLs', ] return Response({'message': 'Hello', 'an_apiview': an_apiview}) def post(self, request): """Create a hello message with our name""" serializer = self.serializer_class(data=request.data) if serializer.is_valid(): name = serializer.validated_data.get('name') message = f'Hello {name}' return … -
How do I launch custom application on client machine from Django web page
I am writing a Django based web application. Following is what I need to achieve Check if the custom application is already installed on the client machine (mostly Windows based) If the application is installed then launch the same from the web page If not installed, push the application to client machine from the web page for user to install (Done) Upon clicking on the stop button on webpage the application on client machine should stop I am reading more about deeplink on web for same, however most of it is for mobile browsers and app is in mobile device If anybody has done this, I would really appreciate if you share the design approach. -
What is the 'to=' positional argument in ForeignKey?
In my project (I am learning Django, so it's a very basic one) I am trying to implement a relationship such as 'an order can have multiple meal items'. So after checking the documentation, I realised that this can be rather implemented as 'a meal item can be in one ore more orders' through the use of the ForeingKey field class. On the Django documentation page for ForeignKey it is said: 'Requires two positional arguments: the class to which the model is related and the on_delete option.' But just passing these two arguments and trying to make the migrations throws an error: TypeError: __init__() missing 2 required positional arguments: 'to' and 'on_delete' Now, my Meal class in models.py looks like so: class Meal(models.Model): name = models.CharField(max_length=15) price = models.DecimalField(max_digits=4, decimal_places=2) order = models.ForeignKey(Order, on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('meals:detail', kwargs={'id': self.id}) I think the problem is due to the fact that the two classes (Order and Meal) are implemented as two different apps (not even sure if that's the way to organise things for reuse). So back to the documentation, when I look to the arguments for ForeignKey it doesn't say anything about the to= positional argument. … -
How to use the GET method in order to fetch data that's saved in the POST method via Django DRF API call?
I want to create an API that allows me to save an image using the POST method via APIView in Django Rest Framework. The image that's saved in the POST method should be displayed within the GET method in the API webpage. The image that's stored is not saved in a model but in a local directory. I don't wish to grab the image name from the directory via the GET method since I will be saving image(s) in a server in the near future. However, I would like to make the process dynamic enough so that the GET method can capture/fetch the image name data immediately after a user uploads and submits an image using POSTMAN. How can this be done? Currently, this is what I had done so far: class API(APIView): parser_classes = (MultiPartParser,) #Need to display the image name here that was saved using the POST method below. def get(self, request, *args, **kwargs): image_filename = self.request.GET.get('image') return Response({'image_name' : image_filename}, status=200) def post(self, request): #key is 'image', value is the file uploaded in the system data = self.request.data #image that gets uploaded img_file = data['image'] if img_file: uploaded_file = img_file image = [{"image_name": uploaded_file}] return Response(image, status … -
difference between url pattern urls in django
What is the difference between 1. url(r'^$', views.Home.as_view(), name='home'), and 2. url(r'^.*', views.Home.as_view(), name='home'), in view.py: class Home(TemplateView): template_name = "index.html" Output of 1 is it will redirect only to index.html when clicked on the other it says Not Found The requested resource was not found on this server. output of 2nd is: it shows UI pages but backgroup django application apis doesnt execute. -
How to store simplejwt token into database
I'm using django-rest-framework-simplejwt for user registration. Following this tutorial enter link description here I code like following: class RegistrationSerializer(serializers.ModelSerializer): password = serializers.CharField( style={'input_type': 'password'}, write_only=True, ) password2 = serializers.CharField( style={'input_type': 'password'},max_length=20 ) tokens = serializers.SerializerMethodField() class Meta: model = UserProfile fields = ['username', 'email', 'password', 'password2', 'tokens'] def get_tokens(self, user): user = UserProfile( email=self.validated_data['email'], username=self.validated_data['username'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) user.set_password(password) tokens = RefreshToken.for_user(user) refresh = text_type(tokens) access = text_type(tokens.access_token) data = { "refresh": refresh, "access": access } return data def save(self): user = UserProfile( email=self.validated_data['email'], username=self.validated_data['username'] ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords must match.'}) user.set_password(password) user.save() return user in view: class UserCreateView(generics.CreateAPIView): '''create user''' serializer_class = RegistrationSerializer The problem is each time I create a user,I can get the return of the 2 two tokens,however in data base I can't find the token. So I guess I didn't store them,so should I store the token? -
How to create a django package without setting DJANGO_SETTINGS_MODULE as environment variable?
I am creating a package that itself uses Django and I will be using it within other Django applications. The main issue I am facing is that I need to use to settings for various reasons such as logging and other extensive requirements. Since, this package does not have any views/urls, we are writing tests and using pytest to run them. The tests will not run without the settings configured. So initially I put the following snippet in the __init__ file in the root app. import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_package.settings") django.setup() Now, the test ran properly and the package as standalone app was working. But the moment I installed it in the main project, it overrides the enviroment variable with it's own settings and you can imagine the kind of havoc it would ensue. This is the first time I am packaging a django app. So I am not well-versed with best practices and the docs are a little convoluted. I read the structure and code of various packages that use settings in their package but I am still not able to understand how to ensure the package accesses the intended settings and the project's settings is not affected … -
How to pass image(any file) from VueJs front end to Django Rest Framework API?
I can upload a file on my Django admin site or from my API but I don't know how to do it from my index.html. I am using axios and tried let data = new FormData(); data.append('file', file) too i just dont know what DRF expect from me and if possible give me some example -
Django app loads slow only for a single view (queries are prefetched and posts are paginated too)
Background I created a free language learning service called LangCorrect.com. It's a place where you can practice writing in a language that you are learning and it will be matched with users who have that language set as their native language. Problem Originally I had all of the journal posts being loaded at once that means three tabs times x # of language posts written. It easily displayed over 70 journal entries at once. I then implemented pagination, but instead of that fixing the problem, it's taking around 3-5 seconds for the page to load. This is only happening on /journal/ On my old staging server which was running a clone of my one week old production server, it was loading super fast. I had to destroy that droplet for reasons, and I made a copy of the latest production server to use as the staging server. But now the staging server is having the same weird issue as my production server. I have no idea where to proceed from here. You can access the service with the following credentials (u: upworkdev pw: textcorrect) and the see the issue here https://langcorrect.com/journal/ What I checked There aren't any issues I can … -
Python: How to convert a list of dates into a list of days for meetings
I am working on a web app in Python/Django and I am trying to make a calendar. I am using Python's HTMLCalendar class found in the calendar module. I have the following in models.py: class Meeting(models.Model): id = models.AutoField(primary_key=True) admin = models.ForeignKey(CustomUser, on_delete=models.CASCADE) name = models.CharField(max_length=20, null=True) location = models.CharField(max_length=200, null=True) start_date = models.DateTimeField(default=None, null=True) end_date = models.DateTimeField(default=None, null=True) description = models.CharField(max_length=2000, null=True) The start_date of the meeting is displayed in the following format: 2019-12-03 00:00:00. I am overriding the formatday() function in HTMLCalendar. This function takes a day as a one of its parameters. I have a list of meetings, and if the meeting is on the day that is passed to the function, I want the calendar to display those meetings on the cell for that day in the calendar. For example, say that the day I am considering is the 3rd of a certain month. I want to somehow be able to extract the day of a meeting from the start_date value (e.g. extract the day 3 from the date 2019-12-03). However, I am not what is the best way to do this. Any insights are appreciated. -
Django Stripe SCA 3D Secure Authentication Failure Creates Open Invoice
When a customer tries to pay, but they fail the 3D secure authentication, an open invoice gets created which is undesirable. Then when a customer finally succeeds their 3D secure authentication, they will now have paid for their subscription PLUS they will have an additional count of open outstanding invoices they will need to pay depending on how many times they failed authentication. I need a way to void the invoice or stop the invoice from being created unless the customer succeeds authentication so that no open outstanding invoices get created. Video: https://streamable.com/2z8nk Code: https://dpaste.de/Jfxu https://dpaste.de/2Y37 Tried doing this: http://dpaste.de/561t https://dpaste.de/3Shs Options to fix: 1) Listen for the invoice.updated event, and if the invoice has status "open" fetch the payment_intent and if it's status is requires_payment_method then void the invoice. https://stripe.com/docs/webhooks/build#create-endpoint 2) Send an Ajax request from your client to your server when authentication fails here -> errorElement.textContent = result.error.message. 3) Do not create the new subscription at all. Re-use the incomplete subscription that was tried earlier. Customer comes, they try to pay, create a Subscription, but the charge fails, so you end up with an incomplete subscription. The subscription has its invoice in latest_invoice opened. That invoice has a … -
How to make a selection button inside a multistep form wizard in Django that renders an output without proceeding to the next step?
I am new to Django and I am making a project with a multistep form using django-formtools. The problem is, in my step 2 form, I have selection fields that I need to pass in the backend to perform some calculations and then render the output. The user can make changes anytime based on the output. I made an apply changes button which should trigger the backend process and a proceed to next step button if the user decides to finalize the selected changes. However, when I click the apply changes button, it leads me to the next step instead. Here's my HTML code: <form action="" method="POST"> {% csrf_token %} {{ wizard.management_form }} {% if wizard.form.forms %} {{ wizard.form.management_form }} {% for form in wizard.form.forms %} {{ form }} {% endfor %} {% else %} {{ form }} # three selection fields <button name="apply_changes">Apply Changes</button> {% endif %} {% if wizard.steps.prev %} <button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans '&#8249; Previous Step' %}</button> {% endif %} <input type="submit" value="{% trans 'Finish' %}"> </form> Here's my SessionWizardView method code snippet: def get_context_data(self, form, **kwargs): context = super(StepWizard, self).get_context_data(form=form, **kwargs) if self.steps.current == 'step_1': # save step 1 data to sessions if … -
Should I use JWT or Sessions for my eCommerce website?
I'm building an eCommerce website for a personal project. It uses React for the front-end and a REST API running on django for the back-end. I want the user to be able to add items to a shopping cart and place an order without the need for an account. For guest users, using a session/cookie to store info is great, but when it comes to logged in users, I would want to use the database to store items in a cart. That would require creating a user and giving them an auth token so they can perform necessary actions. So should I use session/cookie authentication or is there a better way to achieve what I want using JWT? -
django.db.utils.IntegrityError: null value in column "id" violates not-null constraint
I want to save data from the Django model to PostgreSQL database with: mymodel.objects.create(title='test') this model only has title and id but it raises this error: django.db.utils.IntegrityError: null value in column "id" violates not-null constraint how can I fix it? why id is not set automatically as always? -
How to concatenate a varibale from a function in a form action with Django?
i want to concatenate a variable in a form action. for example: <form action:"{% url 'addAlumn' ${id} %}" method="POST"> im sure im wrong but i dont have idea how to do this. this is my function: <script> function alumno(obj, obj2, obj3, obj4) { id = obj; var no_certificado = obj2; var nom = obj3; var curp = obj4; $("#nombre").val(nom); $("#cert").val(no_certificado); $("#curp").val(curp); } </script> -
Django 2 models referencing to each other
I'd like to have 2 models called OrderItem and Order in the same py file and they are connecting to each other. Here is my current code but I got the error when making a migration. I was looking at https://docs.djangoproject.com/en/2.2/ref/models/fields/#foreignkey orders.Order.order_items: (fields.E303) Reverse query name for 'Order.order_items' clashes with field name 'OrderItem.order'. HINT: Rename field 'OrderItem.order', or add/change a related_name argument to the definition for field 'Order.order_items'. class OrderItem(models.Model): """Model representing an order item. """ PIZZA_TYPE_CHOICES = [ ('MARGHERITA', 'Margherita'), ('MARINARA', 'Marinara'), ('SALAMI', 'Salami'), ] PIZZA_SIZE_CHOICES = [(i, i) for i in [25, 35, 40]] order = models.ForeignKey( 'Order', on_delete=models.CASCADE) pizza_type = models.CharField(max_length=20, choices=PIZZA_TYPE_CHOICES) pizza_size = models.IntegerField(choices=PIZZA_SIZE_CHOICES) quantity = models.IntegerField(validators=[MaxValueValidator(99)]) def __str__(self): return self.pizza_type class Order(models.Model): """Model representing an order.""" ORDER_STATUS_CHOICES = ( ('NEW', 'New'), ('PROCESSING', 'Processing'), ('DELIVERING', 'Delivering'), ('DELIVERED', 'Delivered'), ) user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='order', on_delete=models.CASCADE) order_items = models.ManyToManyField(OrderItem) order_status = models.CharField(max_length=20, choices=ORDER_STATUS_CHOICES, default=ORDER_STATUS_CHOICES[0][0]) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username How can I solve this? -
Laying out django-markdownx preview widget in a different place
I'm writing a simple notetaking app using Django, and I have come across django-markdownx. In short, it's great and it's exactly what I need, however I'm having an issue with laying out preview widget to be where I want. So, currently, the rendered text is displayed below my textarea, and I want them side by side. I found this, but haven't successfully tailored it so it suits my needs. The widgets seem to be dependant upon each other, i.e. they have to go into the same template, and I would like to lay them out the way I want in my own template which looks roughly like this: <div class="form-wrapper"> <div class="form-header"> Create a new note </div> [...] <form method="POST"> [...] </form> </div> <div class="preview"> <!-- Preview widget should go here --> </div> Can I somehow overcome this issue?