Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
relation "accounts_usergroup" does not exist
class UserGroup(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bio = models.CharField(max_length=3500,blank=True) isprivate = models.BooleanField(default=False) Error relation "accounts_usergroup" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "accounts_usergroup" I did the following for migrations: python3 manage.py makemigrations <app-name> python3 manage.py migrate Everything else works fine but my new addition of models are not working. I don't want to drop the database as app is in production. I don't know why i am getting this error.Can somebody help please? -
When to use *args , *kwargs in python and django
I would like to clarify the following confusion for python and also for django. I understand that you use args when you are not sure how many non-keyword arguments you have and you use kwargs when you are not sure how many keyword arguments you have. However, I am having some confusion as to when to write args and kwargs and when to use something like a keyword eg slug in my views.py in django and for python functions in general. Take for example: def home_page(request, *args, *kwargs): def login_page(request, username): Why can't I use: def login_page(request, *args, *kwargs): Wouldn't it be better that I use *args, *kwargs instead of username since I wont limit myself to the number of variables I can have in my view? Does it have something to do with the URLs too? I understand that if it is (request, username) in views.py, my urls.py will need to have a /login/<username>, so if it is *args, *kwargs, what should it be? -
Trouble understanding what this noReversematch error means
Hey guys I've ran into NoReverseMatch errors before and generally they're quite easy to fix, normally I haven't done the URLs correctly. I'm a bit taken back with understanding this specific error Im just wondering could anyone shed some light on it for me. Thank you Below is the error shown in powershell. django.urls.exceptions.NoReverseMatch: Reverse for 'prod_detail' with arguments '(<django.db.models.query_utils.DeferredAttribute object at 0x000002885125BF10>, UUID('3676f70a-4089-42ba-8eb9-ed760c9e455e'))' not found. 1 pattern(s) tried: ['(?P<category_id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/(?P<product_id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/$'] [21/Mar/2021 13:47:05] "GET / HTTP/1.1" 500 188352 -
Heroku Application Error on django with react
So Everything is fine during deployment in my django and react as frontend project but still, when I try to open the website I get Application Error and it says to do heroku logs --tail to check logs and when I did some errors were shown. P.S:Everything works perfectly during localhost -
Remove the relation with an object from a ManyToManyField (from admin page and/or from view.py)
I have two models Community and User. In the Community model I am creating a field ManyToManyField called member (based on the User Model) i.e. a community object may have many members and a member object may belong to many communities. The issue I am encountering is that I cannot remove a member from a community neither from within the class-based view.py nor from within the admin page . Creating the ManyToMany relation between Community and User with the field name member. class Community(models.Model): member = models.ManyToManyField(User, related_name='member') Code in class-based view.py for removing a member from a community object (removing only the relation, not the related object itself) class CommunityListView(ListView): model = Community def get(self, request, *args, **kwargs): # The url contains the community id (pk) community_id = kwargs['pk'] c = Community.objects.get(id=community_id) u = User.objects.get(id=self.request.user.id) c.member.remove(u) The code is executed without error but when I visit the admin page the member is still there. I have tried to run c.save() after the command c.member.remove(u) but without success either. As I have understood, Django doc says that the method save() is not needed when you remove a relation from a ManyToManyField. Furthermore, as you can see from the attached image … -
multiple singup using social account authentication in djagno
searching too much about this but not get relative stuff. Goal : signup multiple user using social account authentication(google, facebook, apple) in Django. had tried about Django all-auth couldn't solve the problem. any related source ? -
Config CircleCI for Django and MySQL
I'm using CircleCI to build my DRF API. I have been trying for several hours to configure CircleCI with Django and Mysql. While building the application the container circleci/mysql:8.0.4 failed I'm getting this error: Events status: LLA = Last Locked At LUA = Last Unlocked At WOC = Waiting On Condition DL = Data Locked Next activation : never 2021-03-21T13:04:42.752174Z 0 [Warning] [MY-010315] 'user' entry 'mysql.infoschema@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752193Z 0 [Warning] [MY-010315] 'user' entry 'mysql.session@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752203Z 0 [Warning] [MY-010315] 'user' entry 'mysql.sys@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752212Z 0 [Warning] [MY-010315] 'user' entry 'root@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752228Z 0 [Warning] [MY-010323] 'db' entry 'performance_schema mysql.session@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752236Z 0 [Warning] [MY-010323] 'db' entry 'sys mysql.sys@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752247Z 0 [Warning] [MY-010311] 'proxies_priv' entry '@ root@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752349Z 0 [Warning] [MY-010330] 'tables_priv' entry 'user mysql.session@localhost' ignored in --skip-name-resolve mode. 2021-03-21T13:04:42.752358Z 0 [Warning] [MY-010330] 'tables_priv' entry 'sys_config mysql.sys@localhost' ignored in --skip-name-resolve mode. Exited with code 1 CircleCI received exit code 1 My .conf.yml: version: 2 jobs: build: docker: - image: circleci/python:3.6.7 - image: circleci/mysql:8.0.4 command: ["mysqld", "--character-set-server=utf8mb4", "--collation-server=utf8mb4_bin"] environment: - MYSQL_ROOT_HOST: '%' - MYSQL_ROOT_PASSWORD: root - MYSQL_USER: root - … -
Django two model inheritance one model?
Given the following code:(don't mind the Fields there're just for illustration) Models class UserModel(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) Fields class CommonInfo(models.Model): delete = models.BooleanField(default=False) Fields class MyModel(CommonInfo, UserModel): my_name = models.CharField(max_length=50, blank=False, null=False) Fields Serializer class MySerializer(views.APIView): class Meta: model = MyModel fields = '__all__' Views class MyViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MySerializer This upside model, Serializer & Views use. I use in Django REST Framework. but when I call MyModel they give me an error. This error following: init() takes 1 positional argument but 2 were given -
Show an animation on the website while the ML model is being trained. (Django)
So I am building a website in Django, and within that website, there is an option to train a Machine Learning model which only available to the admin(superuser). However, the model does take some time to train. So is it possible to show some animation to the user, while the model is being trained. And once the model has been trained, the animation will stop and the user will be redirected to another page. I did a bit of exploration but wasn't able to find anything useful. Thanks in Advance Cheers -
How can I trigger the removal button when I create a new one by a clone method in Jquery?
the mission is when I click on the plus button to add a new search input it has to add a new field with a plus button and removal button (it calls 'times-btn') everything works fine but when I click on the removal button the first one has created is removed only but when I click on any button else it doesn't work. so, How can I trigger the removal button that? search.html <!-- Search formsets --> <div class="search-field"> <h2 class="show"></h2> <form method="get" id="main_search"> <div id="first_search_group" class="form-group row search_repeated search_group"> <div class="col-lg-2 d-inline p-2 word_repeated"> <label style="font-size: large; padding-top: 5px">Sentence or Word</label> </div> <!-- Filter --> <div class="col-lg-2 d-inline p-2"> <select name="formsets_option" id="formsets_option" class="form-control"> {% if formsets_option == 'contains' %} <option id="contains" value="contains" selected>contains</option> {% else %} <option id="contains" value="contains">contains</option> {% endif %} {% if formsets_option == 'start_with' %} <option id="start_with" value="start_with" selected>start with</option> {% else %} <option id="start_with" value="start_with">start with</option> {% endif %} {% if formsets_option == 'is' %} <option id="is" value="is" selected>is</option> {% else %} <option id="is" value="is">is</option> {% endif %} {% if formsets_option == 'end_with' %} <option id="end_with" value="end_with" selected>end with</option> {% else %} <option id="end_with" value="end_with">end with</option> {% endif %} </select> </div> <div class="col-lg-4 d-inline p-2"> … -
How to get booleanfield values that are True
I am building a BlogApp and I am trying to get all the users that's profile's BooleanField are True. What i am trying to do:- I made a feature of Users that are banned and I made a BooleanField for each user, AND i am trying to get all the Users that's profile's BooleanValue is True. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) block_users = models.BooleanField(choices=BLOCK_CHOISES,default=False) The Problem def block_users(request): profile = request.user.profile blocked = Profile.objects.filter(block_users=profile.block_users) context = {'blocked':blocked} return render(request, 'blocked.html', context) When i runthis code, This only shows me user that's value is False. BUT i want users that's Value is True. I have no idea how to get it. Thanks in Advance. Any help would be Appreciated. -
Attribute Error in Django: 'tuple' object has no attribute 'add'
Here are the list of models in models.py CATEGORY_CHOICES = [ ('S', "Shirt"), # (what goes into DB, Shown text) ('SW', "Sports wears"), ('OW', "Outwears") ] LABEL_CHOICES = [ ('P', "primary"), # (what goes into DB, Shown text) ('S', "secondary"), ('D', "danger") ] class Item(models.Model): title = models.CharField(max_length=100, blank=False, default="No Title Added") price = models.FloatField(max_length=3, default=0.00, blank=False) category = models.CharField(max_length=2, choices=CATEGORY_CHOICES, blank=False, default='S') label = models.CharField(max_length=1, choices=LABEL_CHOICES, blank=True, null=True) description = models.TextField(blank=True, null=True) discount_price = models.FloatField(max_length=3, blank=True, null=True) slug = models.SlugField(blank=False, default='Slug-1') def __str__(self): return self.title def get_absolute_url(self): return reverse('item_detailview', kwargs={ 'slug': self.slug }) def get_add_to_cart_url(self): return reverse('add_to_cart', kwargs={ 'slug': self.slug }) class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return self.item.title class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem), start_date = models.DateTimeField(auto_now_add=True), ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username All the views work fine but the problem is with "add_to_cart" function. Here is the function def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] # check if the order item is in the order if order.items.filter(item__slug=item.slug).exists(): order_item.quantity += 1 order_item.save() … -
Django models, get Max value from other table using related_name
I have this django model: class User(AbstractUser): ... class Auction(models.Model): title = models.CharField(max_length=64) description = models.CharField(max_length=1024) ... class Bid(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="bids") auction = models.ForeignKey(Auction, on_delete=models.CASCADE, related_name="bids") price = models.IntegerField(default=0) ... I want to list some Auction objects from showing max Bid (or last Bid). Note that in the models I used 'bids' as related_name to access Bids from an Auction object. Trying to employ related_name feature, i did this: def index(request): return render(request, "auctions/index.html", { "listings": Auction.objects.all().annotate(price=Max('bids')) }) Appearently, price=Max('bids') returns the max value of id column in bids. But I need max value of price field. I know I can achieve this using raw querries, or looping through results of Auction.objects.all(), but I wonder if there is a way for this in Django's db abstraction methods. -
Telethon automatic reconnection failed in celery task
I am monitoring the messages received from a bot on telegram using the telethon library, the monitoring is started with a celery task on django. When the bot sends a message in the chat, read the message, perform operations and through a special bot send the result of the operations in a group. The problem is that after several hours of running, I get the following errors which cause the task to close [2021-03-20 21:35:23,415: INFO/ForkPoolWorker-4] Closing current connection to begin reconnect... [2021-03-20 21:35:23,417: INFO/ForkPoolWorker-4] Closing current connection to begin reconnect... [2021-03-20 21:35:23,424: INFO/ForkPoolWorker-4] Connecting to 149.155.157.91:443/TcpFull... [2021-03-20 21:35:23,426: INFO/ForkPoolWorker-4] Connecting to 149.155.157.91:443/TcpFull... [2021-03-20 21:35:33,439: WARNING/ForkPoolWorker-4] Attempt 1 at connecting failed: TimeoutError: [2021-03-20 21:35:33,441: WARNING/ForkPoolWorker-4] Attempt 1 at connecting failed: TimeoutError: [2021-03-20 21:35:44,458: WARNING/ForkPoolWorker-4] Attempt 2 at connecting failed: TimeoutError: [2021-03-20 21:35:44,460: WARNING/ForkPoolWorker-4] Attempt 2 at connecting failed: TimeoutError: [2021-03-20 21:35:55,466: WARNING/ForkPoolWorker-4] Attempt 3 at connecting failed: TimeoutError: [2021-03-20 21:35:55,468: WARNING/ForkPoolWorker-4] Attempt 3 at connecting failed: TimeoutError: [2021-03-20 21:36:06,484: WARNING/ForkPoolWorker-4] Attempt 4 at connecting failed: TimeoutError: [2021-03-20 21:36:06,486: WARNING/ForkPoolWorker-4] Attempt 4 at connecting failed: TimeoutError: [2021-03-20 21:36:10,551: WARNING/ForkPoolWorker-4] Attempt 5 at connecting failed: OSError: [Errno 113] Connect call failed ('149.155.157.91', 443) [2021-03-20 21:36:10,553: WARNING/ForkPoolWorker-4] Attempt 5 at connecting failed: OSError: … -
New file created inside Django App to seed data
I've created an application inside my django project called SeedData. I've added then a file called import_data.py where I will be reading csv files and adding them to my database. -SeedData --__pycache__ --migrations --__init__.py --admin.py --apps.py --import_data.py -- etc.. But whenever i do the following: from Product.models import Product from Category.models import Category from SubCategory.models import SubCategory from Brand.models import Brand import pandas as pd I get this error File "C:\Users\...\SeedData\import_data.py", line 9, in <module> from Product.models import Product ModuleNotFoundError: No module named 'Product' It's the same for Category, SubCategory and Brand. I'd also like to say that the project is fully functional and all the mentioned projects above works perfectly fine. -
Django Channels rest framework: How to get a serialized queryset to the front-end over websocket as "action": "list" is not giving any response
Hey guys I am trying this package hishnas/djangochannelsrestframework and I want to list my chats. I have this function as per the documentation but I am not getting any data in the front-end except a message that the websocket is open. I don't understand what error I am having, please do have a look at the code and help me resolve this. class UserChatListConsumer(ListModelMixin, GenericAsyncAPIConsumer): permission_classes = (IsAuthenticated,) serializer_class = ChatListSerializer # pagination_class = PageNumberPagination def get_queryset(self, **kwargs): if kwargs['action'] == 'list': user = self.scope["user"] chat_list = Chat.objects.by_user(user).order_by('-timestamp') print(chat_list) --> "works and returns the queryset like [Queryset <Chat: (2)>]" return chat_list react front-end socket.onopen = () => ( socket.send(JSON.stringify({"action": "list", "request_id": 42})), console.log('list websocket open') ) socket.onmessage = (e) => { console.log(e) } Thank you -
i am getting error after trying to extend user model using one to one link
error i am receiving AttributeError: 'AnonymousUser' object has no attribute '_meta' my code code inside my models.py class washers(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) mobile=models.IntegerField() added_by=models.CharField(max_length=100,blank=True,null=True) @receiver(post_save, sender=User) def save_user_washers(sender, instance, **kwargs): instance.washers.save() @receiver(post_save, sender=User) def create_user_washers(sender, instance, created, **kwargs): if created: washers.objects.create(user=instance) code inside views.py def wash(request): wf=washerform() uf=Userform() if request.method=="POST": uf=Userform(data=request.POST,instance=request.user) wf=washerform(data=request.POST,instance=request.user.washers) if uf.is_valid() and wf.is_valid(): uf.save() wf.save() return HttpResponse("suscess fully crated ") return render(request,'webpage/washer.html',{'fm':wf,'uf':uf}) -
Postman gives 'this field already exists' while creating a product object in django rest framework
I am trying to make a post api, where a merchant can add products by selecting category, brand, collection in a merchant dashboard. But when I try to send raw json data from the postman, it says category, brand and collection already existed. My models: class Seller(models.Model): seller = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) business_name = models.CharField(max_length=50, blank=True) phone_num = models.CharField(max_length=50, blank=True) class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) My views: class ProductAddAPIView(CreateAPIView): permission_classes = [IsAuthenticated] queryset = Product.objects.all() serializer_class = AddProductSerializer My serializers: class AddProductSerializer(serializers.ModelSerializer): category = CategorySerializer(many=True,required=True) brand = BrandSerializer(required=True) collection = CollectionSerializer(required=True) merchant = serializers.PrimaryKeyRelatedField(read_only=True) variants = VariantSerializer(many=True,required=True) class Meta: model = Product fields = ['id','merchant','category','brand', 'collection','featured', 'top_rated', 'name','description', 'picture','main_product_image','best_seller', 'rating','availability','warranty','services','variants'] # depth = 1 def create(self, validated_data): user = self.context['request'].user category_data = validated_data.pop('category',None) brand_data = validated_data.pop('brand',None) collection_data = validated_data.pop('collection',None) product = Product.objects.create(merchant=user,**category_data,**brand_data,**collection_data) return product My urls: path('api/addproducts', views.ProductAddAPIView.as_view(), name='api-addproducts'), -
cannot cast type integer to uuid Django
Does anybody know why i am getting this error? class Group(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) bio = models.CharField(max_length=3500,blank=True) isprivate = models.BooleanField(default=False) Error File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: cannot cast type integer to uuid LINE 1: ...accounts_group" ALTER COLUMN "id" TYPE uuid USING "id"::uuid -
Saving multiple forms for every file uploaded
I'm new to Django and I'm having a difficulty to create multiple forms for every file that is uploaded. The uploaded files are saved in the media of the server but only one is registered in the database. I have tried multiple ways but I can't seem to make it upload a form for each file attached. This is my models.py class AudioFile(models.Model): title = models.CharField(max_length=100) file = models.FileField() status = models.IntegerField() channels = models.IntegerField() srate = models.IntegerField() prompt = models.TextField() language = models.IntegerField() and this is my views.py def AudioForm(request): if request.method == 'POST': form = AudioFileForm(request.POST, request.FILES) files = request.FILES.getlist('file') if form.is_valid(): for f in files: if isWave(f): form.instance.file = f print('is a wave file') form.instance.status = 0 form.instance.srate = 0 form.instance.prompt = "Testing 123" form.instance.channels = 0 form.save() else: print('is not a wave file') form = AudioFileForm() return redirect('home-page') else: form = AudioFileForm() context = { 'page' : 'Register Audio', 'is_admin' : is_admin(request.user), 'form': form } return render(request, 'users/audioform.html', context) -
How to increment the count of downloads in API
I'm using Django Rest Framework for API, and React JS for frontend, and I need to increment the count of downloads when the button is clicked. I've done that before in Django, but I have no idea how to do that with React. I tried to send the post request to API to increment the count of downloads, but I got this error: Failed to load resource: the server responded with a status of 405 (Method Not Allowed). How to fix it, or maybe there is another way to increment the count of downloads? Here is the data of API: { "id": 3, "category": { "id": 11, "parent": { "id": 2, "name": "Name", "slug": "slug", "img": "Image", }, "name": "system", "slug": null, "img": "" }, "title": "Title", "content": "Content", "image": "", "pub_date": "2022-02-02", "counter": 0, // the count of downloads "file": "file", "in_archive": false } Do I need to create the state of the count of downloads, or there's another way to do that(maybe it has to be in Django)? And here's how I'm trying to send the post request: const SoftwareDetail = ({ match }) => { const [software, setSoftware] = useState([]); const [counter, setCounter] = useState(null); const [file, … -
cx_oracle python and select Like %variable%
I'm trying to execute a query based on "tempo" variable,using %tempo% none of the solution that I found here help my problem import cx_oracle query="""select description, local, point, date from tbl_ext_tempo WHERE point like '%' || :0 || '%' AND ROWNUM<8 ORDER BY date DESC""" cursor.execute(query, tempo) Exception Value: ORA-01036: illegal variable name/number -
Hiding user data of some users from others in django-generic-views
My goal is to allow users to create their own Project instances with nested Task instances. Other users should not have access to data that they did not create. How can I do this correctly? I wrote a custom query set for ProjectListView, but I have problems with other views. Maybe there is a common solution for that case? models.py class Project(models.Model): project_name = models.CharField(max_length=150, default='') user = models.ForeignKey(get_user_model(), null=True, on_delete=models.CASCADE) class Task(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) task_name = models.CharField(max_length=250, default='') is_done = models.BooleanField(default=False) views.py class ProjectListView(LoginRequiredMixin, ListView): model = Project context_object_name = 'projects' def get_queryset(self): return Project.objects.filter(user=self.request.user) class ProjectCreateView(LoginRequiredMixin, CreateView): model = Project fields = ('project_name',) success_url = reverse_lazy('projects') class ProjectUpdateView(LoginRequiredMixin, UpdateView): model = Project fields = ('project_name',) template_name = 'backend/project_update_form.html' success_url = reverse_lazy('projects') class ProjectDeleteView(LoginRequiredMixin, DeleteView): model = Project success_url = reverse_lazy('projects') class TaskCreateView(LoginRequiredMixin, CreateView): model = Task fields = '__all__' success_url = reverse_lazy('projects') class TaskUpdateView(LoginRequiredMixin, UpdateView): model = Task fields = ('task_name', 'is_done',) template_name = 'backend/task_update_form.html' success_url = reverse_lazy('projects') class TaskDeleteView(LoginRequiredMixin, DeleteView): model = Task success_url = reverse_lazy('projects') -
Jinja2 code not recognized and displayed correctly
I searched all around the web and didn't find an answer so hopefully this is not a duplicate. So I am trying to build a browser app using Django and are using some Jinja code in my html file, but the html file when loaded into a browser doesn't recognize Jinja code and only display raw code. In fact after some experimentation I found out that my browser doesn't display correctly any Jinja code. My html file looks like this: <!DOCTYPE html> <html> <head> <title>Music FFT Visualizer</title> <style></style> </head> {% block content %} <body> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload a Song</button> </form> </body> {% endblock %} <html> and my view.py looks like this: from django.shortcuts import render from .forms import MusicVisualizerForm from .models import MusicVisualizer def lastSong(request): MusicVisualizers = MusicVisualizer.objects.all() MusicVisualizer_last = MusicVisualizers[len(MusicVisualizers)-1] return render(request, 'MusicVisualizer/templates/MusicVisualizer.html', { 'MusicVisualizer' : MusicVisualizer_last}) def uploadSong(request): if request.method == 'POST': form = MusicVisualizerForm(request.POST, request.FILES) if form.is_valid(): form.save() else: form = MusicVisualizerForm() return render(request, 'MusicVisualizer/templates/MusicVisualizer.html', {'form' : form}) my webpage looks like this: code1 -
Djonog: storing an ArrayField gives an ambiguous error 'django.db.utils.DatabaseError'
I'm trying to store an ArrayField in a Django model called User, I'm using MongoDB and Djongo. I managed to do it with one model called Pair, I can store a list of Pairs and store that list in a User model using ArrayField which was fairly simple, I just followed this example from Djongo's official doc Now I'm trying to store another list but for some reason, it just keeps giving me a huge TraceBack (90 lines) with an ambiguous error: 'django.db.utils.DatabaseError' here's my user model: class User(AbstractBaseUser): email = models.EmailField(verbose_name='email address', max_length=127, unique=True) first_name = models.CharField(verbose_name='First Name', max_length=30, blank=True) last_name = models.CharField(verbose_name='Last Name', max_length=30, blank=True) is_active = models.BooleanField(default=True, verbose_name='Active') is_admin = models.BooleanField(default=False, verbose_name='Admin') pairs = models.ArrayField ( model_container=Pair, null=True ) conversations = models.ArrayField( model_container=Conversation, null=True ) again, the pairs attribute is working just fine but the conversation is not The Pair model class Pair(models.Model): name = models.CharField(max_length=16) purchase_price = models.DecimalField(verbose_name='Purchase price', max_digits=20, decimal_places=6) class Meta: ordering = ['name'] abstract=True The Conversation model class Conversation(models.Model): handle = models.CharField(max_length=255) class Meta: abstract = True and this is the traceback: Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, sessions, tracker Running migrations: Not implemented alter command for SQL ALTER …