Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + Javascript - How can we verify that the Django value is not null for execute Javascript?
With Django ORM and Javascript: How can we verify that the var1 value is not null? {% for station in stations0 %} var var1 = {{station.punto_comunicacion.latitud}}; if (var1 != None) { latlngs.push(new L.LatLng({{ station.latitud }},{{ station.longitud }})); latlngs.push(new L.LatLng({{ station.punto_comunicacion.latitud}},{{ station.punto_comunicacion.longitud}})); } {% endfor %} Thanks. -
Django: How to create an instance of a model without a form but by a button click
I am new to Django, so pardon me if my question is naive. I am trying to achieve a use case of text mining application on uploaded files, I am trying to show a "Get Started" button in the landing / home page. On button click I am rendering a file upload option. Now I am trying to treat this as a Scan Job, and wanting jobID to get created with the click of the button and the same jobID to be displayed further pages and this jobID to be used as primary key in other models. Below is the model I created. from django.db import models class sfs_job_model(models.Model): sfs_job_id = models.CharField(max_length=250,default="", editable=True) sfs_job_start_date_time = models.DateTimeField(auto_now_add=True, null=False) sfs_job_end_date_time = models.DateTimeField(auto_now_add=True,null=False) sfs_job_status = models.CharField(max_length=250, editable=False,empty_value=None,null=True) sfs_job_summary = models.CharField(max_length=1000) def save(self, *args, **kwargs): if self.job_id is None: self.job_id = 'SFS-' + str(self.id) return super(sfs_job_model, self).save(*args, **kwargs) Please guide me how to achieve the desired use case. Thanks in advance -
Cannot create EmbeddedField in djongo getting this error django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet
hey people I'm new to djongo and was practicing it's usage when i keep getting this error File "D:\python\django Rest webs\tms-REST API\BACKEND\bckend\students\models.py", line 6, in class student(models.Model): File "D:\python\django Rest webs\tms-REST API\BACKEND\bckend\students\models.py", line 7, in student pass_details=models.EmbeddedField(model_container=pass_details, null=True) File "C:\Users\Asus\AppData\Local\Programs\Python\Python38-32\lib\site-packages\djongo\models\fields.py", line 225, in init super().init(model_container, *args, **kwargs) File "C:\Users\Asus\AppData\Local\Programs\Python\Python38-32\lib\site-packages\djongo\models\fields.py", line 87, in init self._validate_container() File "C:\Users\Asus\AppData\Local\Programs\Python\Python38-32\lib\site-packages\djongo\models\fields.py", line 91, in _validate_container for field in self.model_container._meta.get_fields(): File "C:\Users\Asus\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\options.py", line 734, in get_fields return self._get_fields(include_parents=include_parents, include_hidden=include_hidden) File "C:\Users\Asus\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\options.py", line 794, in _get_fields all_fields = self._relation_tree File "C:\Users\Asus\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\Asus\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\options.py", line 707, in _relation_tree return self._populate_directed_relation_graph() File "C:\Users\Asus\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\options.py", line 678, in _populate_directed_relation_graph all_models = self.apps.get_models(include_auto_created=True) File "C:\Users\Asus\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 178, in get_models self.check_models_ready() File "C:\Users\Asus\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\apps\registry.py", line 140, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. MY Code looks like so from djongo import models class pass_details(models.Model): pass_no=models.CharField( max_length=20) class Meta: abstract = True class student(models.Model): pass_details=models.EmbeddedField(model_container=pass_details, null=True) usn=models.CharField(max_length=10) name=models.CharField(max_length=20) objects = models.DjongoManager() -
how to supply command line arguments to appconfig's ready from runserver django
I am working on a django project (consisting of a single app) and want to expose some configuration options for my app through CLI. Inside my cli.py file first I plan to accept these arguments and then use call_command to runserver from django.core.management.commands module. On the other hand in order to do some basic startup activities using the arguments accepted from cli, I have decided to use AppConfig's ready() function for the same. But I am unable to find some bridge using which the accepted cli arguments could be utilized during my application startup (inside ready()). Also the variables created using accepted arguments will be utilized inside my views. How should I design the flow to achieve the same ? -
why is my input fields not showing in the website?
I have created a login and registration page using the same code. The registration page shows username input fields and other fields but the login page only shows the button. Can anyone help me in this Code: Registration Page: <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Sign Up</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a> </small> </div> </div> Login Page: <div class="site-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In </legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Need An Account? <a class="ml-2" href="{% url 'register' %}">Sign Up Now</a> </small> </div> </div> Registration page Login page -
How to store the data of user into pandas dataframe in django app views?
I have created a Measurements model where a user enters the measurement of their daily diabetes. now I want to store the data of a specific user who is logged in from the database into the pandas data frame. How can I do that? my model: class Measurements(models.Model): d_value=models.IntegerField() created=models.DateTimeField(auto_now_add=True) patient=models.ForeignKey(UserSignupModel,on_delete=models.CASCADE) def __str__(self): return str(self.patient) my form: class MeasurementsForm(forms.ModelForm): d_value=forms.IntegerField(help_text="insert the diabetes") class Meta: model=Measurements fields=('d_value',) -
Django: retrieve table data in html page
I have a Django table with 3 fields. I have a total of 4 entries and i want to visualize all of them inside a table which only displays 2 of these 3 fields. How should i do that? i did manage to only display 1 row instead of 4, i'm struggling, someone could help? This is the easy model to manage. class Inc(models.Model): id = models.AutoField(primary_key=True) nr_sin = models.CharField(max_length=50, default=None) nr_pol = models.CharField(max_length=50, default=None) -
Using form field and instance's initial arguments simultaneously instead of the __init__ method
I came across this django tutorial-like blog while trying to learn about django forms ( Link ) It says that using the initial argument in the form field only means that we cannot change the initial arguments for a particular instance of the class, and then starts explaining how to make use of the __init__ method for that exact purpose. A paragraph in the same article states that if we use the initial argument on both the form instance and form fields, form instance's initial values take precedence over any form field (e.g. if you combine the statements from listing 6-9 and listing 6-10, the form will always be pre-filled with email='johndoe@coffeehouse.com' and name='John Doe' from listing 6-9). Can't we just use initial arguments in the form field and then override it if we want to, while creating an instance of the class ? Why do we have to use the __init__ method for the same task? -
How can i structure my API - Django Rest Framework?
I'm redoing an old project of mine but I'm having trouble structuring it in my mind. What my app does : it creates custom reports for shops, based on multiple sources. Those sources are uploaded by the user in the form of multiple CSV files each row of those files linked to the shop id. Right now, what I do is: I upload all the files to my Django app, use a script to process them ( i use panda to clean my CSV files ), and create the report and then add that report to a DB. It works but I think is quite heavy ( there are 800+ shops and 5 CSV files sources + 3 API sources ) and I was wondering if there was a cleaner and simple solution. I'm thinking about using DRF, create a model for each source in a dedicated source app, parse each of the CSV files, and then add them to the DB a table per source. So when I need to create my reports, I'll just fetch the different metrics from the different sources and group them together. It is quite messy in my head, I guess what I'm asking … -
How to deploy a Django application with the Celery task on Heroku Free plan
I need to deploy my Django application which uses Celery on Heroku. The website is already deployed and works fine, but the Celery worker cannot start. Here is the output of the heroku logs -t -p celery command: 2020-05-20T16:37:23.529208+00:00 heroku[celery.1]: State changed from starting to up 2020-05-20T16:37:26.576179+00:00 heroku[celery.1]: State changed from up to crashed 2020-05-20T16:37:26.580191+00:00 heroku[celery.1]: State changed from crashed to starting 2020-05-20T16:37:26.438750+00:00 app[celery.1]: Error: 2020-05-20T16:37:26.438775+00:00 app[celery.1]: Unable to load celery application. 2020-05-20T16:37:26.438776+00:00 app[celery.1]: Module 'forum' has no attribute 'celery' My Procfile: web: gunicorn --pythonpath forum forum.wsgi --log-file - celery: celery worker -A forum -l info -c 4 forum/celery.py file: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'forum.settings') app = Celery('forum') app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() forum/__init__.py file: # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ('celery_app',) Inside the forum/settings.py file I have the following parameters related to Celery: # REDIS related settings REDIS_HOST = 'localhost' REDIS_PORT = '6379' CELERY_BROKER_TRANSPORT_OPTIONS = {'visibility_timeout': 3600} # for Heroku CELERY_BROKER_URL = os.environ.get('REDIS_URL', 'redis://' + REDIS_HOST + ':' + REDIS_PORT + '/0') CELERY_RESULT_BACKEND = os.environ.get('REDIS_URL', … -
Django SuspiciousFileOperation: But Paths are correct
Fellow SOs: From one day to the other day, without making any changes other than installing windows updates, I get this error message: The joined path (C:\Users\X\Y\Z\data\static_files\admin\css\autocomplete.css) is located outside of the base path component (C:\Users\X\Y\Z\data\static_files\) I do know what the error means in general, but as the file is obviously within the base_dir, I dont get what is wrong. The error pops up on every page except for /admin. Settings: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MEDIA_ROOT = os.path.join(BASE_DIR, '../data/media_files/') STATIC_ROOT = os.path.join(BASE_DIR, '../data/static_files/') The setup still works fine on my Mac, but fails on Windows 10 since the last update. Edit: I am using django-pipeline 1.7.0 Any ideas? -
Django (wagtail) serving static with Docker and docker-compose
Dockerfile FROM python:3.7 # Set environment variables ENV PYTHONUNBUFFERED 1 ENV DJANGO_SETTINGS_MODULE project.settings.production RUN apt-get update RUN apt-get -y install apt-utils build-essential libsass-dev RUN apt-get -y install postgresql RUN apt-get -y install postgresql-client COPY ./requirements.txt /code/requirements.txt RUN pip install --upgrade pip # Install any needed packages specified in requirements.txt RUN pip install -r /code/requirements.txt RUN pip install gunicorn # Copy the current directory contents into the container at /code/ COPY . /code/ # Set the working directory to /code/ WORKDIR /code/ RUN useradd my_user RUN chown -R my_user /code USER my_user # collect static files RUN python manage.py collectstatic --noinput --clear CMD exec gunicorn project.wsgi:application --bind 0.0.0.0:8000 --workers 3 EXPOSE 8000 docker-compose.yml version: '3' services: db: # db configuration here web: build: . depends_on: - db volumes: - .:/code environment: - DJANGO_SETTINGS_MODULE=project.settings.dev command: bash -c " python manage.py collectstatic --noinput --clear && python manage.py runserver 0:8000 --insecure" ports: - '80:8000' settings/base.py STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] STATICFILES_DIRS = [ os.path.join(PROJECT_DIR, 'static'), ] # ManifestStaticFilesStorage is recommended in production, to prevent outdated # Javascript / CSS assets being served from cache (e.g. after a Wagtail upgrade). # See https://docs.djangoproject.com/en/3.0/ref/contrib/staticfiles/#manifeststaticfilesstorage STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' # Application static files are collected here STATIC_ROOT … -
Format Output in a particular manner in Django
I want to get all expenses in the format given below.so when I hit the url api/expenses I get the result in following manner and also when I call api/expenses/<id> it shows all expense with that expense id. My Model: class Category(models.Model): name = models.CharField(max_length=40) class Expense(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category_name") description = models.CharField(max_length=200) total_amount = models.IntegerField() class Expense_Details(models.Model): expense = models.ForeignKey(Expense, on_delete=models.CASCADE, related_name="expense") user = models.IntegerField() amount = models.IntegerField() type = models.CharField(max_length=100) ---->type is owe or lend When I request /api/expenses/: Expected Output { “total_expenses”: 10, “Expenses”: [{ “id”: 1, “category”: 1, “created_by”: 1, ------> expense id “description”: “lunch”, “total_amount”: “105”, “owe”: [{ “user_id”: 1, “amount”: 10 }, { “user_id”: 2, “amount”: 95 }], “lend”: [{ “user_id”: 3, “amount”: 10 }, { “user_id”: 4, “amount”: 95 }], }, ... ] } What Query should I use to get Output in the above format ? How will my view look like ? -
django filling database data migration fails
I got following migration in django: # Generated by Django 2.2.12 on 2020-05-20 16:22 from django.db import migrations import re def numeric_version(version): digits = 4 pattern = r"(\d+).(\d+).(\d+)" major, minor, patch = tuple(map(int, re.findall(pattern, version)[0])) return patch + pow(10, digits) * minor + pow(10, 2 * digits) * major def insert_numeric_software_version(apps, scheme_editor): Device = apps.get_model("devices", "Device") for device in Device.objects.all(): if device.software_version is not None: device.numeric_software_version = numeric_version(device.software_version) class Migration(migrations.Migration): dependencies = [ ("devices", "0037_device_numeric_software_version"), ] operations = [insert_numeric_software_version] It should fill the "numeric_software_version" field in the database with numeric fields. In the model this field is: numeric_software_version = models.IntegerField(default=0) When I run "python manage.py migrate" I got following error: File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, … -
Django SQLite working on Heroku production app
I read in lots of places that Heroku doesn't work with SQLite since it's a file DB. I've deployed a Django app to GitHub, including the sqlite db, and then created a Heroku app linked to that DB. When I do things like create a user/fill out forms on the heroku app, it saves the data as expected, and shows it on the page. In other words, it's being stored in the sqlite database since I have not added django-heroku or any postgres functionality myself. Howcome? What am I missing? Why does this work? -
Handling django validation errors and rendering in the template
I am trying to check if my passwords match and throw errors if they do not. It works when they match fine. The only way so far I have managed to see the errors is either in the else statement which just prints or when in the browser it throws the validation error (django error screen). Have read a lot of the docs today and it looks very simple but mine does not comply. view and form underneath def register(request): if request.method == 'POST': form = UserAccountForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: print(form.errors.as_json()) class UserAccountForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) confirm_password=forms.CharField(widget=forms.PasswordInput()) account_email=forms.EmailField() class Meta: model = UserAccount fields = [ 'first_name', 'last_name', 'country', 'account_email', 'password' ] def clean_password(self, *args, **kwargs): password = self.cleaned_data.get("password") confirm_password = self.cleaned_data.get("confirm_password") if password != confirm_password: raise forms.ValidationError("Passwords must match.", code=1) else: return password Ideally I am looking to use the great default stuff django has already. Thank you all :) -
How to adapt this image gallery that uses AJAX to get images on the internet to use it with my django database?
I was looking for an image gallery and I found this on Codepen. Here is the code on Codepen: https://codepen.io/vsync/pen/upeBw And then I searched on the internet and I found the Github repo, they say it is free to use. Here is the Github repo: https://github.com/yairEO/photobox I just wanted to use it with my image gallery on Django. I already spent a lot of hours trying to do it... Could you please take a look if it is even possible to reuse this with Django? HTML <ul id='gallery'></ul> CSS html { min-height: 100%; overflow-y: scroll; background: #000; } body { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; padding: 0; } a { text-decoration: none; } #wrap { overflow: hidden; padding: 3%; } #pbOverlay.show~#wrap { -webkit-filter: blur(2px) grayscale(.4); } #gallery { padding: 20px; } #gallery li { list-style: none; perspective: 100px; -webkit-perspective: 100px; margin: 1px; float: right; position: relative; transition: .1s; -webkit-transition: 0.1s; } #gallery li.video::before { content: '\25BA'; color: #FFF; font-size: 20px; height: 20px; width: 20px; line-height: 0.9; position: absolute; bottom: 3px; left: 4px; z-index: 1; background: rgba(0, 0, 0, 0.4); box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.4); border-radius: 0 3px 0 0; pointer-events: none; opacity: 0; transition: .5s … -
How can I develop voice and SMS cloud services like Twilio and Plivo have?
I'm quite familiar with python and django now I want to develop application like twilio using python and django but i don't have any idea how to start. That's why I'm posting this question. Actually I don't have any idea what are the tools and technology i need to use. do i need to consult with mobile service porivder or somethings else. Please help me. -
Converting like button to Ajax powered like button
I am working on a reverse blog project where users can like and comment. Although I successfully implement the like button to work, But it refreshes the page. My problem is I am trying to convert it to rather use Ajax to power the button. And to as well uses a flag to decide which button to be shown, like or unlike. Please I need help or the logic to guide me on converting the button to work on using Ajax Please Note: I use pagination and the like button is on the list view and detail view (CBV). Thank you in advance. here is my view for the button here is my model here is my template rendering -
Django: validate filefield within the form
I have seen a lot of posts that helped a lot but I am trying to write this validation in a slightly different way but I cannot get it to work Here is what my forms.py look like: class ETL(forms.Form): Historical = forms.FileField() Pre_processing = forms.FileField() Supplier = forms.FileField() parameters = forms.FileField() def process_data(self, url, *args, **kwargs): """ historical data checkout """ content = self.cleaned_data['Historical'] content_type = content.content_type.split('/')[0] if content_type in settings.CONTENT_TYPES and content.size > settings.MAX_UPLOAD_SIZE: fh = io.TextIOWrapper(self.cleaned_data['Historical'].file) #raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(content.file.size))) else: raise forms.ValidationError(_('File type is not supported, check type and size')) """ pre-procesing data checkout """ content = self.cleaned_data['Pre_processing'] content_type = content.content_type.split('/')[0] if content_type in settings.CONTENT_TYPES and content.size > settings.MAX_UPLOAD_SIZE: #if content.size > settings.MAX_UPLOAD_SIZE: fpp = io.TextIOWrapper(self.cleaned_data['Pre_processing'].file) #raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(content.file.size))) else: raise forms.ValidationError(_('File type is not supported')) """ supplier data checkout """ content = self.cleaned_data['Supplier'] content_type = content.content_type.split('/')[0] if content_type in settings.CONTENT_TYPES and content.size > settings.MAX_UPLOAD_SIZE: fs = io.TextIOWrapper(self.cleaned_data['Supplier'].file) #raise forms.ValidationError(_('Please keep filesize under %s. Current filesize %s') % (filesizeformat(settings.MAX_UPLOAD_SIZE), filesizeformat(content.file.size))) else: raise forms.ValidationError(_('File type is not supported')) """ parameters data checkout """ content = self.cleaned_data['parameters'] content_type = content.content_type.split('/')[0] if … -
Embedded youtube videos showing up blank in Django card-columns page
I'm working in a django project and i've run into an issue using embedded videos with bootstraps card-columns. We have a django plugin, Media Player, that simply puts a div & iframe on the page, most of the JS comes from the websites. The videos in question are from youtube, but i've tried vimeo videos and same result. The issue is that some videos work fine, but others don't show up on the page, they are blank/white. However, the video is still there, it takes up space & i can hover over it and see that the Media Player plugin is there. And I can hit the middle of it, where the play button should be and even though I won't see anything I can hear the audio from the video. It's also worth noting that when the page loads, for a brief second I can see the black box of the videos loading but they immediately go white. I can also use the inspect bow in the web browser to see the video exists on the page. I'm using boostrap with cards & the card-columns setup, column-count of 3 at XL, so 3 vertical rows of about 12 cards. … -
django channels share variable between group users
I am developing a online game on django, for real time connection I am using channels but unfortunately for every user I have a separate instance of game. What I want is, for first user I start the game with object of StartGame and want to use this same instance object for other users also, because I want to share current state of game. How can I, share game instance with other members of that group only ? -
email not sending after successful registered : Django
email not sending after successful registered. email not sending to the user email but data is coming properly to the database after successful registered. it would be great if anybody could figure out where i am doing thing wrong. thank you so much in advance. serializers.py class RegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField() username = serializers.CharField(allow_blank=True, label='Username', max_length=30) password = serializers.CharField(write_only=True) token = serializers.CharField(allow_blank=True, read_only=True) class Meta: model = User fields = [ 'username', 'email', 'password', 'token', ] def create(self, data): username = data['username'] email = data['email'] user_queryset = User.objects.filter(Q(email__iexact=email) | Q(username__iexact=username)).first() password = data.pop('password', None) instance = self.Meta.model(**data) subject = "test subject" message = "test message" from_email = settings.FROM_EMAIL to_mail = email if user_queryset == None: if password is not None: instance.set_password(password) instance.save() return instance if subject and message and from_email: try: send_mail(subject, message, from_email, to_mail) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponse('thank you for register!') else: raise serializers.ValidationError("User Already Exists!") views.py class RegisterAPIView(APIView): permission_classes = [AllowAny] serializer_class = RegisterSerializer def post(self, request, format=None): data = request.data register_serializer = RegisterSerializer(data=data) if register_serializer.is_valid(): register_serializer.save() new_register = register_serializer.data return Response(new_register, status=HTTP_201_CREATED) else: return Response({"msg":"invalid credential"}, status=HTTP_400_BAD_REQUEST) -
Django Update view creates new object while also updating
I'm working on a test application in Django and have run in to an issue I've been unable to solve. I have two models, Farm and Product which have a One to Many relationship. When creating a Farm you can add multiple images which gets added as individual products with the Farm as the foreign key. As I was working on being able to update the name of the farm I also wanted to add the ability to add more products on the same page. So I wrote a post function that is similiar to the one I used for creating the farm. However when I submit the update it doesn't only update and add the new products, it also creates a new farm object with the same name. I think I have to get the correct instance for this to work but I don't have enough experience with Django to know where I need to implement those changes. (I might also have to change from the UpdateView to something else, if so please let me know!) Here is my UpdateView: class FarmUpdateView(UpdateView): model = Farm fields = ['title'] def post(self, request, *args, **kwargs): farm = self.get_object() form_class = self.get_form_class() … -
How to set product attributes to basket line and order line in Oscar?
I'm new to Django-oscar and working on Basket now I can add products as lines to the basket easily but what if I want to choose a specific Product attribute to add to basket for example product A has attributes {'size': ['M', 'S'], 'color': ['red', 'blue']} what should I do if I want to add product A with size M and the color blue to the basket? Then I want to store and show the selected option attribute, (for example a customer choose product with color 'red' and size 'M'), then I need to show the selected attributes by the customer in the cart page and order pages also. I have created an attribute of type multi-option, how can I manage this?