Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
running subprocess to capture output for node js
I have a file add.js and it's content is- var add = (a, b) => a + b; const args = process.argv; console.log(add(args[2], args[3])); and when I run it from django using - def cmdline(command): process = Popen( args=command, stdout=PIPE, shell=True, universal_newlines=False ) return process.communicate()[0] print(cmdline("node folder/add.js 10 10")) it is giving - b'1010\n' and when I pass - print(cmdline("node folder/add.js 10")) it's giving - b'10undefined\n' I do not have much experience with js so how do I add them as integers. Thanks -
How to create Article tags from splitting the Title in Django
I want to create articles tags from the title of a RSS feed post. Then save the tags into a DB with a post_id of the title i got the tags from at the same time. Something like this: Title = "Voyant raises $15M to scale production of its tiny, inexpensive lidar tech" Tags = ['Voyant', 'Raises', '$15M', 'To', 'Scale', 'Production', 'Of', 'Its', 'Tiny', 'Inexpensive', 'Lidar', 'Tech'] Assuming the post_id is 1, the Tags table should look like: id | tag | post_id -------------------------------- 1 | Voyant | 1 2 | Raises | 1 I have 3 models in my table(Source, Posts & Tags). class Source(models.Model): name = models.CharField(max_length=500, verbose_name='Website Name') class Posts(models.Model): title = models.CharField(max_length=500, verbose_name='Post Title') source = models.ForeignKey(Source, on_delete=models.CASCADE, verbose_name='Source') class Tags(models.Model): name = models.CharField(max_length=500) post = models.ForeignKey(Posts, on_delete=models.CASCADE, verbose_name='Posts') So so far i was able to split the title above. title = item.title strip_away = title.replace(",", "").replace(":", "").replace("(", "").replace(")", "").replace("'", "").replace("[", "").replace("]", "").replace("!", "").replace("?", "").replace("-", " ") capital = strip_away.title() article_tags = capital.split() But now my problem comes during the saving part. def fetch_articles(): feed = feedparser.parse("my_site_of_preference") source = Source.objects.get(pk=1) source_id = int(source.pk) source_name = source save_new_articles(source_id, source_name, feed) def save_new_articles(source_id, source_name, feed): selected_source_id = source_id … -
Build invite-code user registration Django 4.0
I want build a invite-code registration user system in Django. For registration a new user need to fill two fields of form 'INVITE' (UUID getted from already exists user) and 'PASSWORD'. After send data (requests.POST) Django check invite-code (finds it in the database and correlates it with the user id) and if result is success Django generate 8-symbols username and add new user record in db with fill ID, USERNAME, PASSWORD, INVITER, UUID. For example, the invitation code is the UUID of an existing user. myapp/model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser class Users(AbstractBaseUser): def login_gen(): import uuid uuid = uuid.uuid4() return str(uuid)[:8], uuid id = models.BigAutoField(primary_key=True) username = models.CharField("Username", max_length=8, null=False, blank=False, db_index=True, unique=True, default=login_gen()[0]) password = models.CharField("Password", max_length=255, null=False, blank=False) role = models.BooleanField("Right or Left", null=False, blank=False) inviter = models.ForeignKey('Whos invite', self.id, null=False, blank=False) #... other fields UUID = models.UUIDField("UUID", null=False, blank=False, default=login_gen()[1]) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['username', 'password', 'role'] def __str__(self): return self.username I would like to implement the task with authentication tools built into Django, but I can't cope with the user model (model.py), form (forms.py) and manager (managers.py) in any way. -
Django one to many models - How to create the "many" when the "one" is created?
There are a lot of questions along these lines, but so far as I can tell, but many are quite old and I haven't found one that helped me understand my use case. I think I want to be looking at signals, but I'm not clear on exactly what I should be doing in terms of Django patterns and best practices. Here's my Model code: from django.db import models from django.db.models.fields import SlugField, TextField from django.utils import timezone # Hexes have Terrains, which impart intrinsic properties, like base speed and .png image # They're NOT 1:1 with Hexes IE) You might want Slow and Normal Grasslands with the same image class Terrain(models.Model): FAST = 'F' NORMAL = 'N' SLOW = 'S' SPEED_CHOICES = [ (FAST, 'Fast'), (NORMAL, 'Normal'), (SLOW, 'Slow'), ] name = models.CharField(max_length=64) speed = models.CharField(max_length=6, choices=SPEED_CHOICES, default=NORMAL) image = models.ImageField(upload_to='images/', blank=True) def __str__(self): return self.name # Grids establish the dimensions of a HexMap. Grids may be used in many HexMaps class Grid(models.Model): name = models.CharField(max_length=64) size = models.IntegerField(default=72) num_rows = models.IntegerField(default=10) num_cols= models.IntegerField(default=10) def __str__(self): return self.name # Hexes represent the "tiles" on a Grid. A single Hex may appear in many Grids class Hex(models.Model): name = models.CharField(max_length=64, … -
Implement REST API with Django
This is my Django model: class M(models.Model): a = models.IntegerField() b = models.IntegerField() This is the serializer: class MSerializer(ModelSerializer): class Meta: model = M fields = ['a', 'b'] I would like to be able to implement these REST APIs: 127.0.0.1:8000/m/ (GET list of all elements, POST new element) 127.0.0.1:8000/m/:id/ (GET details of element with id id) 127.0.0.1:8000/n/:a/m/ (GET all elements with a specific a field) So far this is the view and urls that I implemented: class MViewSet(ModelViewSet): queryset = M.objects.all() serializer_class = MSerializer router = DefaultRouter() router.register(r'm', MViewSet) urlpatterns = [ path('', include(router.urls)), ] However, in this way the third use case is not working. How can I modify my code to make the third case work? I'd prefer to use as few lines of code as possible (i.e., I would like to use some Django built-in functionalities). -
Form.as_p works fine but individual form fields is not submitting correctly
I have set up my template by import my form with form.as_p before, and it works fine. However, I need to specify each field, as I have a field that I don't want the user to see (and I need to have it in my django admin so I can't exclude it from the form). However, when I set-up the form with it's individual fields, and submit it, I don't get redirected, I just get back to the filled out form. I have set-up a number of print fields, and have also tried to print in form_invalid but nothing shows up, I have no idea what the issue is. Can someone suggest how to fix this or maybe solve it another way? The form in the template <form method="post" enctype="multipart/form-data" id="adForm" data-municipalities-url="{% url 'ajax_load_municipalities' %}" data-areas-url="{% url 'ajax_load_areas' %}" novalidate> {% csrf_token %} <!-- {{ form.as_p }} --> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.province.errors }} {{ form.province.label_tag }} {{ form.province }} </div> <div class="fieldWrapper"> {{ form.municipality.errors }} {{ form.municipality.label_tag }} {{ form.municipality }} </div> <div class="fieldWrapper"> {{ form.area.errors }} {{ form.area.label_tag }} {{ form.area }} </div> <div class="fieldWrapper"> {{ form.name.errors }} {{ form.name.label_tag }} {{ form.name }} </div> <div … -
Ajax json doesnt show any instances
that even if i connected json data to ajax, it doesnt show me any results. def get_json_categories(request): query_get = request.GET if query_get: query_get = query_get['q'] categories = EcommerceProductCategory.objects.filter(name__contains=query_get).order_by('name') else: categories = EcommerceProductCategory.objects.order_by('name') data = {} data['results'] = [] for category in categories: data_to_return = {} data_to_return['id'] = category.id data_to_return['name'] = category.name data['results'].append(data_to_return) return JsonResponse(data) And i urled that to ecommerce/get_json_categories and in the Django html <div class="mt-2"> <hr> <div class="form-group"> <select class="form-control w-30" name="category_select" id="category_select" aria-describedby="category_select" required></select> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <script> $('#category_select').select2({ placeholder: 'Wybierz kategorię', ajax: { url: 'http://127.0.0.1:8000/ecommerce/get_json_categories', dataType: 'json', data: function (params) { return { q: params.term, page: params.name }; }, } }); </script> But it shows me "No results could be found" but that site (/ecommerce/get_json_categories) is full of json data. -
how to show delete button for modelformset - django
I'm trying to implement an application, which is has two models : Booking and Visitor each booking needs to have several Visitors, so the Visitor should be a formset in order to add several Visitors, but sometimes we need remove unwanted form from the Visitor, {{form.DELETE}} shows a checkbox, but i dont want it be a button, and remove the form right after clicking the button, i need to change here is my models class Booking(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE,default=1) room_no = models.ForeignKey(Room,on_delete=models.CASCADE,blank=True,related_name='rooms') name = models.CharField(max_length=40,default='',blank=True,null=True) class BookingVisitor(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT,related_name='visitor_admin') booking = models.ForeignKey(Booking,on_delete=models.CASCADE,related_name='booking_bookingvisitors') visitor_name = models.CharField(max_length=50) my forms is simple modelform VisitorBookingFormset = modelformset_factory(model=BookingVisitor,form=BookingVisitorForm,can_delete=True) and here is my views def createBooking(request): main_form = BookingForm() visitor_forms = VisitorBookingFormset(queryset=BookingVisitor.objects.none(),prefix='formset') if request.method == 'POST': main_form = CustomerInvoiceForm(request.POST) visitor_forms = VisitorBookingFormset(request.POST,prefix='formset') if main_form.is_valid() and visitor_forms.is_valid(): main_obj = main_form.save(commit=False) main_obj.admin = request.user main_obj.save() for form in visitor_forms: if form.is_valid(): form_obj = imei.save(commit=False) form_obj.booking = main_obj form_obj.save() return JsonResponse({'success':True}) else: return JsonResponse({'success':False,'error_msg_mainform':main_form.errors,'error_msg_visitorform':imei_forms.errors}) context = { 'main_form':main_form, 'visitor_forms':visitor_forms } return render(request,'booking/booking.html',context) and here is my template form <form action="" method="POST" id="create-booking">{% csrf_token %} <div class="row"> <!-- /.col --> <div class="col-md-4 pull-right"> <div class="form-group"> <label>room no</label> {{main_form.room_no | add_class:'form-control text-center'}} </div> </div> <div class="col-md-4 pull-right"> <div class="form-group"> <label>name</label> … -
django how to create a serializer ListField that accepts DictField with images values
As the title describes I need to create a Custom serializer ListField that accepts dictionary of string keys and value of Image Example input: [ {'1':FirstImage} , {'3',ThirdImage} ] What I've tried: customSerializer = serializers.ListField( child=serializers.DictField( child=serializers.ImageField(allow_empty_file=True, use_url=False) ) ) Obviously my serializer doesnt work as it should, anyone have an idea how can I make this work? Thanks In Advance -
How to successfully INCLUDE extra fields & UPDATE/DELETE existing fields(at a go) using either modelformset_factory/inlineformset_factory
i have my models ready, adding new products, that i have figured out, but including extra fields and updating/deleting this newly added field on one html form has been such a pain, the following are my exact codes with slight changes #my models.py class Product(models.Model): title = models.CharField() class ProductSpecification(models.Model): name = models.CharField() class ProductSpecificationValue(models.Model): product = models.ForeignKey(Product) specification = models.ForeignKey(ProductSpecification) value = models.CharField() class ProductImages(models.Model): product = models.ForeignKey(Product) images = models.ImageField(upload_to="images/uploads/") So here i will show my working code for ADDING new Product objects(just incase am doing it wrong, and it has anything to do with why updating part isn't working) #MY Adding product forms.py class AddNewProductForm(forms.ModelForm): title = forms.CharField() class Meta: model = Product fields = ['title',] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].widget.attrs.update{'class': 'form-control'}) class AddNewProductSpecForm(forms.ModelForm): class Meta: model = ProductSpecificationValue fields = ['specification', 'value'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['specification'].widget.attrs.update({'class': 'form-control'}) self.fields['value'].widget.attrs.update({'class': 'form-control'}) class AddNewProductImgForm(forms.ModelForm): #this is to upload multiple img in bulk at one go images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = ProductImages fields = ['images',] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['images'].widget.attrs.update({'class': 'form-control'}) #MY Adding product views.py @login_required def add_new_product(request): AddNewProductFormSet = modelformset_factory(ProductSpecificationValue, form=AddNewProductSpecForm, extra=3) if request.method == "POST": product_form = AddNewProductForm(request.POST, … -
Will ignoring this (ValueError: signal only works in main thread of the main interpreter) affect anything?
I have a Django server running, and when it receives the user's data, it runs a separate program in views.py After it has completed what I have wanted I receive this error both in the terminal and the host server: handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler)) ValueError: signal only works in main thread of the main interpreter So I decided to do: try: #code except ValueError: return redirect('home') Which works perfectly fine as it redirects to the homepage of my website. Will it affect my website in the future when multiple users use the website? -
Override Save Model Django
I would like to override the save model in Django, to ensure a check that my User doesn't follow himself/herself. I know I can do this using serializer and put a check in view but I want to learn how to override def save. class Followable(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) followers = models.ManyToManyField(User, related_name="users", null=True, blank=True) class Meta: abstract = True def save(self, *args, **kwargs): if self.user != self.followers: return ValidationError("User cannot follow oneself.") super(Followable, self).save(*args, **kwargs) I tried printing out *args and **kwargs but it is empty. Also, User is my custom User Model. -
Staticfiles won't serve in production for Django application in Heroku
I am new both to Django and to project-deployment. I have gone trough all of the files a million times now, and I still cannot find what went wrong. The website itself gets displayed, but without any CSS, images or JavaScript. I would really appreciate any help. Here is the settings file import os import sys from .cdn.conf import * import mimetypes mimetypes.add_type("text/css", ".css", True) BASE_DIR = Path(__file__).resolve().parent.parent STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] DEBUG = os.getenv("DEBUG", "False") == "True" DEVELOPMENT_MODE = os.getenv("DEVELOPMENT_MODE", "False") == "True" ALLOWED_HOSTS = ['scienz.herokuapp.com'] INSTALLED_APPS = [ 'main.apps.MainConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'crispy_forms', 'storages', ] CRISPY_TEMPLATE_PACK = 'bootstrap4' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' ROOT_URLCONF = 'scienZ.urls' -
Why do I get this error in django when I run this command?
python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\commands\runserver.py", line 115, in inner_run autoreload.raise_last_exception() File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\core\management\__init__.py", line 381, in execute autoreload.check_errors(django.setup)() in wrapper fn(*args, **kwargs) File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\y\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\apps\config.py", line 223, in create import_module(entry) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2544.0_x64__qbz5n2kfra8p0\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'hellodjango' -
How to add comment on django site with ajax call and without refreshing?
On site exists form where users able to comment products. Comments are connected with products. Jqery is used from Boostrap base.html.(it's worked with another ajax-call) I'm fighting with ajax comment during the week) Trying to do it only for one product to understand how it works. Without ajax system of comments works fine, but I decided to add smooth in comment add without refreshing of the page and I do task with POST and ajax for the first time (before I did two pretty simple examples with get and form reset after succesfull response to ajax from back-end). Could somebody advice what should be add in template and view ? I suppose problem is connected with my poor knowledge of js. I'am using "is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'" cause this working with django 4.0, and old function is_ajax() was removed. views.py def ajax_test(request): product = Product.objects.get(id=4) comments = product.comment_set.order_by('-created_at') form = UserCommentForm context = {'product':product,'comments':comments,'form': form} return render(request, 'store/ajax_test.html', context) def ajax_receiver(request): is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' if request.method == 'POST' and is_ajax: product = Product.objects.get(id=4) form = UserCommentForm(data=request.POST) user = Comment.objects.get(author=user) if form.is_valid() and request.user.is_authenticated: new_comment = form.save(commit=False) new_comment.author = request.user new_comment.product = product new_comment.save() comment_info = { "author": … -
making hash of data in django rest framework serializers
i want to making a SHA256 hash of some fields in my serializer and set it to another field in the same serializer, this is my model: class Something(models.Model): x = models.CharField(max_length=300) y = models.IntegerField() z = models.IntegerField() f = models.IntegerField() hash = models.CharField(max_length=300) first user defines x,y,z and f. after that i need to generate hash automaticly like this hash = x + y + z + f my serializer : class SomethingSerializers(serializers.ModelSerializer): class Meta: model = Something fields = ['x', 'y', 'z', 'f', 'hash'] what is the best decision? -
Push rejected, failed to compile python project - Django , Heroku
It is my first deployment, I am trying to push my django project into heroku but it is saying push rejected; failed to compile python project. i have tried changing the python lower versions but no luck. Any help would be much appreciated!! Thanks. Here, is my cmd output > (blog-rHhqYg-f) C:\projects\blog>git push heroku master > Enumerating objects: 72, done. > Counting objects: 100% (72/72), done. > Delta compression using up to 4 threads > Compressing objects: 100% (67/67), done. > Writing objects: 100% (72/72), 22.87 KiB | 2.86 MiB/s, done. > Total 72 (delta 25), reused 0 (delta 0), pack-reused 0 > remote: Compressing source files... done. > remote: Building source: > remote: > remote: -----> Building on the Heroku-20 stack > remote: -----> Determining which buildpack to use for this app > remote: -----> Python app detected > remote: -----> No Python version was specified. Using the buildpack default: pyt > hon-3.9.9 > remote: To use a different version, see: https://devcenter.heroku.com/art > icles/python-runtimes > remote: cp: cannot stat '/tmp/build_9e902a87/requirements.txt': No such file or > directory > remote: -----> Installing python-3.9.9 > remote: -----> Installing pip 21.3.1, setuptools 57.5.0 and wheel 0.37.0 > remote: -----> Installing dependencies with Pipenv … -
How to set field value expiration time?
I have model User like this: class User(AbstractBaseUser, PermissionsMixin): myfield_choices = (('foo', 'First value'), ('bar', 'Second value') myfield = CharField(choices=choices) objects = BaseUserManager() I set in the field myfield value foo. After I want to set in the field myfield value bar for 1 day and after this period expires, the value becomes foo again automatically. How can I set that expiration time? Is there any native django instruments for this? -
Plotly.js for tidy data - Bar color
I’m new to plotly JS, but I have good experience with python - I want to get the same results as the following: import plotly.express as px long_df = px.data.medals_long() fig = px.bar(long_df, x="nation", y="count", color="medal", title="Long-Form Input") fig.show() Essentially to use the data value to add distinct colors to my bars, is there any easy way to obtain that results?, obviously I have a tidy dataset <script> $(document).ready(function(){ var xValue = {{ date|safe }}; var yValue = {{ revenue|safe }}; var stage = {{ stage|safe }}; var Forecast = { x: xValue, y: yValue, type: 'bar', text: yValue.map(String), textposition: 'auto', hoverinfo: 'none', name:'Leads', marker: { color: 'rgba(255, 99, 132, 0.2)', opacity: 0.8, line: { color: 'rgba(255, 99, 132, 1)', width: 1.5 } } }; var data = [Forecast]; var layout = { title: 'Sales Forecast - Leads and Deals', barmode: 'stack' }; var config = {responsive: true} Plotly.newPlot('DivBarChart', data, layout, config); }); </script> What I want to do is to color the graph based on the Stage: Year Month Stage Revenue Date Cumulative 0 2022 Feb Lead 750.0 Feb-2022 NaN 1 2022 Mar Lead 16172.5 Mar-2022 NaN 2 2022 Apr Lead 43617.0 Apr-2022 NaN 3 2022 Oct Deal 120000.0 … -
Django double join with multiple models?
I've spent quite some time on it and still haven't been able to figure out how to join these tables with django. I have a Movie database with following models: class Movies(models.Model): MovieName = models.CharField(db_column='MovieName', primary_key=True, max_length=30) MovieRating = models.FloatField(db_column='MovieRating') MovieReleaseTime = models.DateTimeField(db_column='MovieReleaseTime') class Genre(models.Model): GenreID = models.IntegerField(db_column='GenreID', primary_key=True, max_length=30) GenreTitle = models.CharField(db_column='GenreTitle', unique=True, max_length=30) class MovieGenres(models.Model): MovieName = models.ForeignKey('Movies', models.DO_NOTHING, db_column='MovieName') GenreID = models.ForeignKey('Genre', models.DO_NOTHING, db_column='GenreID') In my PostgreSQL I can pair MovieName with GenreTitle using following query: SELECT "MovieName", "GenreTitle" FROM public."Movies" NATURAL JOIN public."MovieGenres" NATURAL JOIN public."Genres"; I then get something like this: MovieName | GenreTitle -----------|------------ MovieA | GenreA MovieA | GenreB MovieB | GenreA How can I achieve the same output with Django views? -
Django update formset not saving
Simple recipe database with an update form, but when adding a new ingredient to an existing recipe, it's not saving the update. I'm not getting any error message either. The setup is user goes go a recipe list and is presented with a create button for new recipes and a list of existing recipes with an update button next to the recipe name. When the user clicks the update button, it takes them to /recipe_update/#/ and is presented with the list of ingredients. It should allow them to add/remove/change ingredients and percent, and then save the changes, but it's not saving new ingredients or changes. models.py class Recipe(models.Model): name = models.CharField(max_length=200, null=True) description = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.name class Recipe_Ingredient(models.Model): recipe_name = models.ForeignKey(Recipe, null=True, on_delete = models.SET_NULL) ingredient = models.ForeignKey(Product, null=True, on_delete= models.SET_NULL) recipe_percent = models.DecimalField(max_digits=8, decimal_places=5, blank=True) views.py def recipeUpdate(request, recipe_id): recipe = Recipe.objects.get(pk=recipe_id) recipeingredient = inlineformset_factory(Recipe, Recipe_Ingredient, fields=('ingredient', 'recipe_percent',)) if request.method == 'POST': formset = recipeingredient(request.POST, instance=recipe) if formset.is_valid(): formset.save() return redirect('/') formset = recipeingredient(instance=recipe) context = {'formset':formset} return render(request, 'accounts/recipe_form.html', context) urls.py ... path('recipe_update/<recipe_id>/', views.recipeUpdate, name="recipe_update"), ... recipe_form.html {% extends 'accounts/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-md-6"> … -
Django model field values returning blank?
I'm a Django Beginner. I have a model named "Person" with two character fields - first_name and last_name. I have migrated them using makemigrations in the shell and have set the value of first_name to my first name. However, whenever I try to set a value for last_name it returns blank. For example: a = Person(last_name="...") a.save() a.id id=... Person.objects.get(id=...) <Person: > The value will just be blank in the brackets. Here is my models.py if it's relevant: from django.db import models class Person(models.Model): first_name = models.CharField(max_length=15) last_name = models.CharField(max_length=6) def __str__(self): return self.first_name I'm not entering a value that is beyond the max_length. Thanks for your time. -
Django CKEditor does not work in all textarea fields
I have tried to use Django CKEditor to improve my text editor. It looks good; however not all my textarea fields can be impacted by Django CKEditor. It only influences at the first one, others don't.Here are my pictures and code. Hopefully you can help me solve the problem. Thank you! enter image description here enter image description here post-detail.html <section id="comments"> {% for child_comment in comment.children %} <div class="child-comment"> <a href="mailto:{{ comment.user.email }}" style="text-decoration: none;">{{ child_comment.author }}</a> <span style="font-style: italic;">{{child_comment.timestamp}}</span> <p>{{child_comment.text|safe}}</p> </div> {% endfor %} </section> <section id="comment-form"> <form action="{% url 'post-detail-page' post.slug %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for form_field in comment_form %} <div class="form-control {% if form_field.errors %}invalid{% endif %}"> {{ form_field.label_tag }} {{ form_field }} {{ form_field.errors }} {{ form.media }} </div> <button>Submit</button> {% endfor %} </form> </section> <script type="text/javascript" src="{% static "ckeditor/ckeditor-init.js" %}"></script> <script type="text/javascript" src="{% static "ckeditor/ckeditor/ckeditor.js" %}"></script> views.py @class_view_decorator(login_required) class PostDetailView(View, LoginRequiredMixin): def is_marked_post(self, request, post_id): marked_posts = request.session.get('marked_posts') if marked_posts is not None: is_saved_for_later = post_id in marked_posts else: is_saved_for_later = False return is_saved_for_later def get(self, request, slug): post = Post.objects.get(slug=slug) context = { "post": post, "post_tags": post.tags.all(), "comment_form": CommentForm(), "comments": post.comments.all().order_by("-id"), "saved_for_later": self.is_marked_post(request, post.id) } return render(request, "blog/post-detail.html", context) def … -
How to set Authorization header in Django?
I want to set the bearer token in the authorization header. why? Because I am using rest_framework_simplejwt in my Django project. I want to implement authorization using JWT. For that, I create an access token and save it in cookies on user login. Now I want to check if the access token which is stored in the cookie is invalid or expired? So, the user can see the data fetched from DB. Let me tell you some more detail then I will be able to tell you my problem. As you can see in the image I changes the token in the cookie but when I refreshed it it just shows that I am login. Can you please tell me the flow of Auth. in rest_framework_simplejwt. here is the code. https://i.stack.imgur.com/vAtxz.png https://i.stack.imgur.com/9htCS.png https://i.stack.imgur.com/HFgvp.png https://i.stack.imgur.com/ftJIA.png https://i.stack.imgur.com/Bh2At.png https://i.stack.imgur.com/3Hl6e.png https://i.stack.imgur.com/1kE5a.png -
Making a post http request of form data to a database with empty/blank fields
I have a consumer model with several fields, where I have also specified their default values; e.g. age = models.CharField(default="no information", max_length=50) I use the following snippet to post a new consumer to my MongoDB database: if request.method == 'POST': try: consumer_data = JSONParser().parse(request) consumer_serializer = ConsumerModelSerializer(data=consumer_data) if consumer_serializer.is_valid(): consumer_serializer.save() collection_name.insert_one(consumer_serializer.data) response = { 'message': "Successfully uploaded a consumer with id = %d" % consumer_serializer.data.get('id'), 'consumers': [consumer_serializer.data], 'error': "" } return JsonResponse(response, status=status.HTTP_201_CREATED) else: error = { 'message': "Can not upload successfully!", 'consumers': "[]", 'error': consumer_serializer.errors } return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST) except: exceptionError = { 'message': "Can not upload successfully!", 'consumers': "[]", 'error': "Having an exception!" } return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR) When I fill out all the fields on my Angular form and post, everything works fine. However, when I leave a field blank, I get a bad request error message and the post does not go through. Initially, I thought it was because I did not have default fields in my Django model, but even after I added them, I still get this. How can I modify the code snippet to allow me to post with blank fields? This not only saves me time in testing and filling out the form …