Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use Javascript to implement a username taken function in my registration form?
So I'm loading my registration form into my html and then using a for loop to iterate over those fields. I am wondering where I can add form control to show a green box around my username field so that a user knows if a username is taken before hitting the submit button. I tried adding it to the form tag and setting a div tag around {{field}} but neither of those work. Furthermore, how can I make it ONLY for Username? I understand I need to use JavaScript for this, but I'm still new to coding and I haven't touched Javascript at all, so no idea how and where to place JS code in my code reg.html {% block content %} <br> <h1 class="text-center" style="color:#f5387ae6">Register to fall in love today!</h1> <form method="post" style="width:700px;margin:auto" action="{% url 'dating_app:register' %}" enctype="multipart/form-data" class= "form" > {% bootstrap_form registration_form%} {% csrf_token %} {% for field in bootstrap_form %} <p> <div class="form-control is-valid"> {{field.label_tag}} {{field}} </div> {% if field.help_text %} <small style="color:grey;">{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style="color: red;">{{error}}"</p> {% endfor %} </p> {% endfor %} <div class="form-check"> <input type="checkbox" id="accept-terms" class="form-check-input"> <label for="accept-terms" class="form-check-label">Accept Terms &amp; Conditions</label> </div> <div> … -
How to add a link to a template form to extend the form to the corresponding id?
Currently I have a form consisting of updating an objects, based on the models below. class Product(models.Model): CATEGORY = ( ('Sports', 'Sports'), ('Fashion', 'Fashion'), ('Toys', 'Toys'), ('Electronics', 'Electronics'), ('Kitchen', 'Kitchen'), ('Jewellery', 'Jewellery'), ) product_sku = models.AutoField(primary_key=True) name = models.CharField(max_length=200, null=True) category = models.CharField(max_length=200, null=True, choices=CATEGORY) description = models.CharField(max_length=200, null=True, blank=True) r_price = models.FloatField(null=True) d_price = models.FloatField(null=True, blank=True,default='') start_date = models.DateTimeField(null=True, blank=True,default='') end_date = models.DateField(null=True, blank=True,default='') tags = models.ManyToManyField(Tag) stock = models.CharField(max_length=200, null=True) min_stock = models.CharField(max_length=200, null=True) def __str__(self): return self.name def get_image_filename(instance,filename): id = instance.product.id return "picture_image/%s" % (id) def path_and_rename(instance, filename): upload_to = 'images' ext = filename.split('.'[-1]) if instance.pk: filename = '{}.{}'.format(instance.pk, ext) else: filename = '{}.{}'.format(uuid4().hex, ext) return os.path.join(upload_to, filename) class Picture(models.Model): product_pic = models.ImageField(null=True, blank=True,upload_to=path_and_rename) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL ) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.product.name I have a form of updating the Product model, see below for its view, form and template views.py @login_required(login_url='login') def EditProduct(request,pk): product_list = Product.objects.all().order_by('product_sku') product = Product.objects.get(product_sku=pk) form = ProductForm(instance=product) if 'edit_product' in request.POST: if request.method =='POST': form = ProductForm(request.POST, instance=product) if form.is_valid(): form.save() return redirect('/') context = {'form':form} return render(request, 'accounts/edit_product_profile.html',context) forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields = ['product_sku','name','category','description','r_price','d_price','start_date', 'end_date','stock','min_stock'] Template <div class="row"> <div … -
How to load static files from separate S3 bucket when hosting site on Elastic Beanstalk Aws React Django
Setup: React+Django hosted on Elastic Beanstalk. Static files hosted on separate S3 Bucket. I'm trying to load an image using src="/static/images/logo.png". In development it works perfectly, but in production it sends a request to XXX.elasticbeanstalk.com/static/images/logo.png while it should be requesting Bucket.amazonaws.com/static/images/logo.png. Meanwhile the user uploaded media is working perfectly for both POST and GET requests, images are stored and fetched from the Bucket /media/ path. I want to avoid conditionally coding the absolute url path depending on the environment. I have a django production_settings.py file: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, "..", "www", "static") STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' AWS_STORAGE_BUCKET_NAME = '****************' AWS_S3_REGION_NAME = '****************' AWS_ACCESS_KEY_ID = '****************' AWS_SECRET_ACCESS_KEY = '****************' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATICFILES_LOCATION = 'static' STATICFILES_STORAGE = 'custom_storages.StaticStorage' MEDIAFILES_LOCATION = 'media' DEFAULT_FILE_STORAGE = 'custom_storages.MediaStorage' custom_storages.py: from django.conf import settings from storages.backends.s3boto3 import S3Boto3Storage class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION class MediaStorage(S3Boto3Storage): location = settings.MEDIAFILES_LOCATION Thanks -
Reload template variable without refreshing in django
I will auto update template variable without refresh web page when spark streaming finished in view.py view.py spark = SparkSession.builder.appName("Python Spark SQL basic example").config("spark.some.config.option", "some-value").getOrCreate() schema = StructType().add("_c0", "integer").add("InvoiceNo", "string").add("Quantity","integer").add("InvoiceDate","date").add("UnitPrice","integer").add("CustomerID","double").add("TotalSales","integer") INPUT_DIRECTORY = os.path.join(os.path.dirname(__file__), "../jsonFileInput") OUTPUT_DIRECTORY = os.path.join(os.path.dirname(__file__), "../jsonFileOutput") CHECKPOINT_DIRECTORY = os.path.join(os.path.dirname(__file__), "../writestream_checkpoints") dataStream = spark.readStream.format("json").schema(schema).load(INPUT_DIRECTORY) query = dataStream \ .writeStream \ .format("json") \ .option("checkpointLocation",CHECKPOINT_DIRECTORY) \ .option("path", OUTPUT_DIRECTORY) \ .start() def dashboardV2 (request): df = spark.read.format('json').schema(schema).option('header',True).load(OUTPUT_DIRECTORY) totalSales = codeData.totalSales(df) ncustomer = codeData.allCustomer(df) return render(request,'dashboardV2.html',{ 'totalSales': totalSales, 'ncustomer': ncustomer }) I need to auto update totalSales and ncustomer variable in template when streaming data. (df variable will read json file that spark streaming and use it to calculate in function for totalSales and ncustomer variable) template.html <!DOCTYPE html> <html> <body> <label class="valueTotalSales2017">$ {{totalSales}} M</label> <label class="valueNumCus2017">{{ncustomer}}</label> </body> </html> codeData.py spark = SparkSession.builder.appName("Python Spark SQL basic example").config("spark.some.config.option", "some-value").getOrCreate() def totalSales(df): total = df.select('TotalSales').groupby().sum().toPandas() total = total['sum(TotalSales)'][0]/1000000 # convert to millions total = "%.2f" % total # trim 2 decimal return total def allCustomer(df): ncus = df.select('CustomerID').distinct().count() return ncus Thank for your helping. -
How to create an interface/form in django where the user can use tools such as bold and italicize before submitting (similar to tools in google docs)
I am making a django website where a user inputs an essay. I want to the user to be able to use tools in order to "prettify" their essay by changing font, color, and other elements, and use tools such as bold and italics. For example, if you see the interface where you can ask a question in stack overflow, you can see formatting information on the top. Stack Overflow Create Question Tools -
Django postgre super user connection issue
File "/app/.heroku/python/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 185, in get_new_connection 2020-06-03T18:40:44.102875+00:00 app[web.1]: connection = Database.connect(**conn_params) 2020-06-03T18:40:44.102876+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/psycopg2/init.py", line 127, in connect 2020-06-03T18:40:44.102876+00:00 app[web.1]: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) -
How do you get a django model instance from an Angular select dropdown field containing a django-rest-api field with a foreignkey?
I have an application that runs Angular on the client side and Django on the backend, im using Django-request-framework for my model serialization, whereby my model has a model named Job which in turn has a field named job_category which points to a model JobCategory in a foreignkey relationship like this models.py JobCategory(models.Model): title = models.CharField(max_value=100) Job(models.Model): title = models.CharField(max_value=200) job_category = models.ForeignKeyField(JobCategory, on_delete=models.CASCADE) So on my angular component i have a select field which loops over the job categories like this Angular component html form <select id="category" class="form-control color-gray" ngModel name='category'> <option *ngFor='let category of job_categories' [ngValue]="category.id" >{{ category.title }} </option> </select> everything works fine at that point until i select a job category from the Angular options and post it, then i get the error that "ValueError at /api/jobs/↵Cannot assign "'Companion Care'": "Job.job_category" must be a "JobCategory" instance. how can i fix this or how do you select an instance of JobCategory? -
Django clear rest api urls for function based views
I am writing the code using function based views ( I have some reasons for it ), and I need to solute one trouble. I want to have clear urls (like posts/id for detail view and the same posts/id for update view and posts/id for delete view ). But I don't know how we can do it using just usual function based views. I have tried to remove /update, /create/ delete/ from my views, but without that it doesn't work :) I suppose it happens because Django doesn't know, which request is for posts/id ( it might be get detail request, update or delete ). Could you help me? My urls for posts: from django.urls import path from posts.views import ( api_detail_post_view, api_create_post_view, api_update_post_view, api_delete_post_view, api_list_post_view ) app_name = "posts" urlpatterns = [ path('', api_list_post_view, name="list"), path('<int:post_id>/', api_detail_post_view, name="detail"), path('<int:post_id>/update/', api_update_post_view, name="update"), path('create/', api_create_post_view, name="create"), path('<int:post_id>/delete/', api_delete_post_view, name="delete"), ] -
Re-writing of the raw query
I had written a SQL raw query in python for the Postgres database. However, the following query I wrote for was when my Song field in my Django model was a many-to-many field. But, due to other requirements, the same Song field in the model has been changed to the foreign key. The issue, I am facing is that the query doesn't runs successfully and returns an error. I had written two raw Postgres queries: raw query:(Using left join) select songs.id, songs.name, songs.artist, songs.album, songs.albumart, songs."albumartThumbnail", cpr.votes, is_requested from ( select id, name, artist, album, albumart, "albumartThumbnail" from ( select song_id from core_plsongassociation where playlist_id in (1477) ) as sinpl left join songs on sinpl.song_id=id where explicit=False ) as songs left join ( select song_id, votes, bool_or(thirdpartyuser_id=177) as is_requested from ( select * from core_priorityrequests where client_id=2876 and is_played=False ) as clpr left join core_priorityrequests_third_party_user on clpr.id=priorityrequests_id group by priorityrequests_id, song_id, votes ) as cpr on songs.id=cpr.song_id left join ( select core_blockedsongs_song.song_id from core_blockedsongs join core_blockedsongs_song on core_blockedsongs.id=core_blockedsongs_song.blockedsongs_id where core_blockedsongs.unblock_flag = 'f' and core_blockedsongs.client_id=2870 ) as c on c.song_id = songs.id where c.song_id is null; My Model in Django is as follows: class BlockSong(models.Model): client = models.ForeignKey('Client') playlist = models.ForeignKey('Playlist', … -
Run manage.py with custom database configuration
My use case involves running python manage.py migrate with DATABASE_HOST=127.0.0.1 (since I use Cloud SQL Proxy). However, when the application is uploaded and is serving, the database URL needs to change to an actual remote URL. Right now, I upload a special settings.py file that contains the localhost URL when I wish to run the migration command. When I deploy to cloud, I make sure to overwrite that file with a new one (which is essentially the entire file except the database URL is my remote db URL) and then upload it. Is there a better way to achieve this? Something like python manage.py --database_url=127.0.0.1 migrate? -
Read HTML Response and print urls in Django
Im new to Django. Basically i have page where it has all city names, i have added them using admin page and models. Now if i click on any City name it should route to that city's wiki page. My question is how can i get the city name which i have clicked and how can i dynamically pass those city names in URLS appedning the city name to it and call individual wiki page. Here is my html snippet of city, where dests.name is my city name {%for dests in dests%} <!-- Destination --> <div class="destination item"> <div class="destination_image"> <img src="{{dests.image.url}}" alt=""> {% if dests.offer %} <div class="spec_offer text-center"><a href="#">Special Offer</a></div> {% endif %} </div> <div class="destination_content"> <div class="destination_title"><a href="destinations">{{dests.name}}</a></div> <div class="destination_subtitle"> <p>{{dests.desc}}</p> </div> <div class="destination_price">From ${{dests.price}}</div> </div> </div> {%endfor%} My present view has code to check user authentication and load sample html when clicked on city name class Destinations: def destinations(request): # Login.login(request) if request.user.is_authenticated: return render(request,'sample.html') else: print("In Destinations else loop") return redirect('login') -
How to get an url with username as slug parameter django rest framework
i have a balance model with onetoone field with Users models, so every user have a "balance" relationated with themselves. This is my model: class Balance(models.Model): user = models.OneToOneField(User, blank=True, on_delete=models.CASCADE) balance = models.DecimalField(default=0, max_digits=8, decimal_places=2, blank=True) @receiver(post_save, sender=User) def create_balance(sender, instance, **kwargs): if kwargs.get('created', False): Saldos.objects.get_or_create(user=instance) print('created balance model to user') This is my Serializer from django.contrib.auth.models import User from rest_framework import serializers class OwnerSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['username'] class BalanceSerializer(serializers.ModelSerializer): user = OwnerSerializer(read_only=True) class Meta: model = Saldos fields = '__all__' This is my view from .models import Balance from rest_framework import viewsets from .serializers import BalanceSerializer class BalanceViewSet(viewsets.ModelViewSet): queryset = Balance.objects.all() serializer_class = BalanceSerializer And this is my urls.py from django.urls import include, path from rest_framework import routers from .views import BalanceViewSet router = routers.DefaultRouter() router.register(r'api/balance', BalanceViewSet) urlpatterns = [ path('', include(router.urls)), ] This works fine, problem is that i'd like to the url for every single user be something like http://127.0.0.1:8000/api/balance/username instead of http://127.0.0.1:8000/api/balance/1 Is there any way to put the username that is related that balance in url ? Regards -
Django: Can't get the value of a RadioSelect to validate my form
I'm quite new to django, what I want to do: I have several music files and I want to let the user choose which music file he likes. I can display all files in a fieldset with radiobuttons to chose one file. What the html site looks like But when I try to proceed I get the following error: AttributeError at /creation/music 'list' object has no attribute 'get' Request Method: POST Request URL: http://localhost:8000/creation/music Django Version: 2.2.10 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'get' Exception Location: C:\Users\ssi\AppData\Local\Programs\Python\Python37-32\lib\site- packages\django\forms\widgets.py in value_from_datadict, line 652 Python Executable: C:\Users\ssi\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.1 Python Path: ['D:\\Dropbox\\dev\\django_project', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\python37.zip', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\DLLs', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32', 'C:\\Users\\ssi\\AppData\\Roaming\\Python\\Python37\\site-packages', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\win32\\lib', 'C:\\Users\\ssi\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\Pythonwin'] Server time: Mi, 3 Jun 2020 14:26:43 +0000 For the form I used the following code (forms.py): class VideoMusicForm(forms.ModelForm): def __init__(self, round_list, *args, **kwargs): super(VideoMusicForm, self).__init__(*args, **kwargs) self.fields['music'] = forms.CharField(widget=forms.RadioSelect(choices=round_list)) class Meta: model = Video fields = ['music'] In my views.py I defined the following function: def makemusic(request): lst = getSamples() if request.method == 'POST': form = VideoMusicForm(request.POST, lst, instance=request.user.video) if form.is_valid(): form.save() return redirect('overview') else: form = VideoMusicForm(lst, instance=request.user.video) else: form = VideoMusicForm(lst, instance=request.user.video) return render(request, 'videomaking/music.html', {'form':form}) Here is the html file for this … -
How to pass multiple values from models.py to HTML via views.py in Django
I have a following models.py for my Django blog, I made a following views.py to pass the value of the slug for my URL parameter. However I am struggling to create a model in views to get other data(person & description) from Category class. I have tried some patterns by myself but can not pass them to HTML. (always Error or not showing) Can you please give me some idea of how to solve this. models.py class Category(models.Model): person = models.CharField(max_length=20) description = models.TextField() slug = models.SlugField() def __str__(self): return self.person views.py def blog_category(request, category): posts = Post.objects.filter(categories__slug__contains=category).order_by("-created_on").distinct() context = {"category": category, "posts": posts} return render(request, "blog_category.html", context) HTML(Localhost:8000/slug) {{ person }} {{ description }} -
Django manual form creating whitespace in between objects in option list
When this form renders it is creating a whitespace between options - as if you can select whitespace as an option. <div class="form-group col-md-6 mb-0"> <label>Select Category</label> <select id="categories" name="categories" class="form-control"> {% for category in form.category %} <option id="{{ category.id }}" value="{{ category.id }}"> {{ category }} </option> {% endfor %} </select> </div> What is wrong? -
How to get list of object(equipement) for each object (intervention) manytomany relationship in django
models equipement https://i.stack.imgur.com/38e6o.png models intervention https://i.stack.imgur.com/8V1JL.png models intervention with relationship manytomany so when i add a new "intervention" it will add to table of association https://i.stack.imgur.com/KZZcd.png i need to list all equipement of each intervention this is my view : https://i.stack.imgur.com/Mtnqf.png and this is when i list all intervention int template html https://i.stack.imgur.com/LSvzv.png -
How to remove objects from ManyToMany Field in Django Rest Framework neasted serializer?
I can successfully add a new object(s) into notification_days but what is the most idiomatic way to handle removing any object(s)? models.py DAYS_OF_WEEK = ( (0, 'Mon'), (1, 'Tue'), (2, 'Wed'), (3, 'Thu'), (4, 'Fri'), (5, 'Sat'), (6, 'Sun'), ) class WeekDay(models.Model): day = models.IntegerField(choices=DAYS_OF_WEEK) def __str__(self): return self.get_day_display() class Company(models.Model): name = models.CharField(...) notification_days = models.ManyToManyField(WeekDay) serializers.py class WeekDaySerializer(serializers.ModelSerializer): id = serializers.IntegerField(required=False) day_display = serializers.SerializerMethodField() class Meta: model = WeekDay fields = ['id', 'day', 'day_display'] def get_day_display(self, obj): return obj.get_day_display() class CompanySettingsSerializer(serializers.ModelSerializer): notification_days = WeekDaySerializer(many=True) class Meta: model = Company fields = [ 'name', 'notification_days' ] def update(self, instance, validated_data): notification_days = validated_data.get('notification_days') for day in notification_days: day_id = day.get('id', None) if item_id: if not instance.notification_days.filter(pk=day_id).exists(): week_day = WeekDay.objects.get(pk=day_id) instance.notification_days.add(week_day) return instance api.py class CompanySettingsAPIView(RetrieveUpdateAPIView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsCompanyAdmin, ) serializer_class = CompanySettingsSerializer def get_object(self): return Company.objects.get(pk=self.kwargs.get('pk')) Sample GET response: { "name": "Django", "notification_days": [ { "id": 1, "day": 0, "day_display": "Mon" }, { "id": 2, "day": 1, "day_display": "Tue" }, { "id": 3, "day": 2, "day_display": "Wed" } ] } -
Field Error during Password reset in Django custom user
I have a custom User in my django app. And when I submit an email to reset password in the the built in password reset form, I get the following error FieldError at /password_reset/ Cannot resolve keyword 'is_active' into field. Choices are: active, address, admin, bio, company_category, company_desc, company_name, company_site, country, designation, email, first_name, grad_year, id, last_login, last_name, linkedin, logentry, markets, no_employees, password, phone, photo, resume, staff, technologies, university My custom user model and model manager are as follows: # ----------------------------- USER MANAGER ----------------------------- class UserManager(BaseUserManager): def create_user(self, email, password=None, is_active=True, is_staff=False, is_admin=False): if not email: raise ValueError("Users must have an email address") if not password: raise ValueError("Users must have a password") user_obj = self.model( email = self.normalize_email(email), ) user_obj.staff = is_staff user_obj.admin = is_admin user_obj.active = is_active user_obj.set_password(password) user_obj.save(using=self._db) return user_obj def create_staffuser(self, email, password=None): user = self.create_user( email, password=password, staff=True, admin=True ) return user def create_superuser(self, email, password=None): user = self.create_user( email, password=password, is_staff=True, is_admin=True ) return user # ----------------------------- CUSTOM USER ----------------------------- class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) resume = models.FileField(upload_to='res/', blank=True, null=True, verbose_name='resume') photo = models.ImageField(upload_to='pi/', default='img/default.png', blank=True, null=True) bio = models.CharField(max_length=1000) designation = models.CharField(max_length=255) university = models.CharField(max_length=255) company_name = … -
Django 3: Adding Data to DetailView
I have a very similar question to this and this and my guess is I overlooked something. I want to query related objects (foreign keys) from the model in the template: models.py: class PartBase(models.Model): name = models.CharField('Name', max_length=120) price = models.DecimalField("Price per part", decimal_places=2, max_digits=6) class Sett(models.Model): name = models.CharField('Name', max_length=120) class PartRelation(models.Model): part = models.ForeignKey(PartBase, on_delete=models.CASCADE) qty = models.PositiveIntegerField("Quantity") sett = models.ForeignKey(Sett, related_name='setts', on_delete=models.SET_NULL, null=True) views.py: class SetDetailView(DetailView): model = Sett context_object_name = "setts" template: {% for p in setts.partrelation_set.all %} <p>value: {{ p.get_part_price }}</p> {% endfor %} Problem: empty HTML page - so setts.partrelation_set.all is empty / does not exist. What I tried was adding a queryset to the view class: class SetDetailView(DetailView): model = Sett context_object_name = "setts" queryset = Sett.objects.all() def get_queryset(self): return self.queryset.filter(setts = self.kwargs.get("Sett_id")) But I took a wrong turn here somewhere. What I also tried is adding a lot of return attribute methods in the model and so I could get it to work in the shell - but not in the DetailView. -
No module named 'django.utils.six'
I cannot add img on admin site after use cloudinary on my django project. It will show error: No module named 'django.utils.six'. Does anything else need to setup? cloudinary config on setting.py: INSTALLED_APPS = [ ... 'cloudinary_storage', 'django.contrib.staticfiles', 'cloudinary', ... ] MEDIA_URL = '/media/' DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' CLOUDINARY_STORAGE = { 'CLOUD_NAME': '***', 'API_KEY': '***', 'API_SECRET': '*****', } urls.py: urlpatterns = [ ... ]+ static(settings.MEDIA_URL, document_root=settings.DEFAULT_FILE_STORAGE) models.py: class article(models.Model): title = models.CharField(max_length=200) content = RichTextField() slug = models.SlugField(unique=True) default='article_img/coming_soon.jpg') article_img = models.ImageField(upload_to='article_img', blank=True) status = models.IntegerField(choices=STATUS, default=0) topic = models.IntegerField(choices=TOPIC, default=0) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='article') -
How to remove/add many to many object in Django Rest Framework?
models.py DAYS_OF_WEEK = ( (0, 'Mon'), (1, 'Tue'), (2, 'Wed'), (3, 'Thu'), (4, 'Fri'), (5, 'Sat'), (6, 'Sun'), ) class WeekDay(models.Model): day = models.IntegerField(choices=DAYS_OF_WEEK) def __str__(self): return self.get_day_display() class Company(models.Model): name = models.CharField(...) notification_days = models.ManyToManyField(WeekDay) serializers.py class CompanySettingsSerializer(serializers.ModelSerializer): class Meta: model = Company fields = [ 'name', 'notification_days' ] api.py class CompanySettingsAPIView(RetrieveUpdateAPIView): authentication_classes = (SessionAuthentication, ) permission_classes = (IsCompanyAdmin, ) serializer_class = CompanySettingsSerializer def get_object(self): return Company.objects.get(pk=self.kwargs.get('pk')) Sample GET response: { "name": "Django", "notification_days": [ 1, 3 ] } I can send PUT with added or removed IDs in notification_days but how can I have objects instead of IDs and be able to update/remove it in PUT request? -
In my django project, a guest user inputs 3 or 4 records and takes printout the processed data. How to retrieve those records only
A guest user visits my site and enters some records in my model db. After he should view only those records only. My database already has some records. I want to list only this sessions records only. -
How do I allow my django website to be hosted by a local server (127.0.0.1) and a Heruko server
I don't know if I am explaining my problem correctly but I can clarify with the following picture of my settings.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: don't run with debug turned on in production! # DEBUG = True DEBUG = False # ALLOWED_HOSTS = [] ALLOWED_HOSTS = ['sheryar-portfolio.herokuapp.com', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', 'calculator', 'amino' ] 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', ] Now here in ALLOWED_HOSTS, I have declared two hosts. The Heroku one is running perfectly whereas I am having some issues in the local one. It seems like that my static folder is not being located by django as I can only see the HTML of my website in local server. In short, I cannot see the CSS being applied to my website when I am including the local server in ALLOWED_HOST -
Celery Queues and after_task_publish
I'm trying to monitor my celery queues and which tasks they are running. The main idea is to get a better understanding of how everything works. I'm fairly new to celery outside of calling delay or setting up a periodic_task. I'm running into a bit of a pickle, no pun indented and I'm using datadog to monitor some of this information. What I setup is an after_task_publish function that I'd like to use to track the task and queue it was processed on. I actually would like the worker as well. I have extended my celery results so I can look things up in redis and see the queue. @after_task_publish.connect() def on_task_publish(sender=None, headers=None, body=None, **kwargs): task = app.tasks.get(sender) task_name = task.name queue_name = ( task.__dict__.get("_exec_options").get("queue") if task is not None else "unknown" ) tag = f"{queue_name}:{task_name}" statsd.increment("celery.on_task_publish.increment", tags=[tag]) Currently the tasks _exec_options queue is always None. Below is an example. {'queue': None, 'routing_key': None, 'exchange': None, 'priority': None, 'expires': None, 'serializer': 'json', 'delivery_mode': None, 'compression': None, 'time_limit': None, 'soft_time_limit': None, 'immediate': None, 'mandatory': None} Now this I don't understand because I set the queue, and also know the job ran so it had to be queued. sender.add_periodic_task( 10.0, health_check_background_crawls.s(), name="health_check_background_crawls", … -
Django Python - SQLDecodeError on deleted attribute after Migration
I am currently using Django2.2 with Djongo1.2.38, and running into a SQLDecodeError - DuplicateKey after I changed the model and ran a migration. I had a model, Project, that had an attribute called customer_po. I removed this attribute and changed around a bunch of attributes, and made/applied a migration. I can see in the output from making my migration this line: - Remove field customer_po from project I applied my migration and it was successful. I created a new project object, and when I go to create a second one I am met with this error: FAILED SQL: INSERT INTO "crud_project" ("id", "project_number", "purchase_order", "quotation_number", "client_name", "project_name", "project_owner_id", "project_manager_id") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s, %(6)s, %(7)s) Params: (UUID('eb7184ee-cc0c-4765-a04c-455a2a70af15'), '123', '12345', '321312', 'Hello', 'Ads', UUID('30f86ee3-e1b7-4820-a39e-c996a1799254'), UUID('c29f869a-e629-46b3-9cc6-cace7de1b987')) Pymongo error: {'writeErrors': [{'index': 0, 'code': 11000, 'keyPattern': {'customer_po': 1}, 'keyValue': {'customer_po': None}, 'errmsg': 'E11000 duplicate key error collection: psm.crud_project index: customer_po_1 dup key: { customer_po: null }', 'op': {'id': UUID('eb7184ee-cc0c-4765-a04c-455a2a70af15'), 'project_number': '123', 'purchase_order': '12345', 'quotation_number': '321312', 'client_name': 'Hello', 'project_name': 'Ads', 'project_owner_id': UUID('30f86ee3-e1b7-4820-a39e-c996a1799254'), 'project_manager_id': UUID('c29f869a-e629-46b3-9cc6-cace7de1b987'), '_id': ObjectId('5ed7c79ddfacbb6c0315927a')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} Even though the attribute is not in the params, or inside the …