Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
POST http://127.0.0.1:8000/authentication/register 403 (Forbidden)
i am working on a django project and i faced this error and I am unable figure out what mistake I have done , this is a subpart of project where in this I am building a registration form using django and ajax this is the error that I got register.js:6 POST http://127.0.0.1:8000/authentication/register 403 (Forbidden) This is my Register.html file , I used csrf_token also {% extends 'base_auth.html' %} {% load static %} {% block content %} <br> <br> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <div class="card"> <div class="card-body"> <div class="card-title py-2"> <h4>Register Here</h4> </div> <form class="" action="index.html" method="post"> {% csrf_token %} <div class="form-group"> <input type="text" name="Username" id="username-field" class="form-control"> </div> <div class="form-group"> <input type="email" name="email" id="email-field" class="form-control form-control-sm"> </div> <div class="form-group"> <input type="password" name="password" id="password-field" class="form-control form-control-sm"> <small class="float-right py-3">SHOW</small> </div> <input type="submit" value="register" class="btn btn-primary btn-block "> </form> </div> </div> </div> </div> <div class="col-md-4"></div> </div> <script type="text/javascript" src="{% static 'js/register.js' %}"> </script> {% endblock %} this is my views.py file from django.shortcuts import render from django.views import View from django.views.decorators.csrf import csrf_exempt # Create your views here. import json from django.contrib.auth.models import User from django.http import JsonResponse class RegistrationView(View): def get(self,request): return render(request,'authentication/register.html') class UserNameValidationView(View): def post(self,request): data = … -
converting a Django ValuesListQuerySet object to a float
i have time data saved (in epoch time) in a MySQL database as a IntegerField. i'm doing some data visualisation where i'd like to show orders by the hour and by day of the week as bar charts, so i'd like to convert these epoch times to date time objects and visualise the data accordingly. however, datetime.datetime.fromtimestamp() only takes in floats and i've been having issues converting my IntegerField to anything other than a list. (i've also tried converting the resulting list to a float, but get a Type Error: float() argument must be a string or a number). i'm wondering if i should continue to find a way to convert my epoch time (Django ValuesListQuerySet object) in my views.py file, or if i should just return my epoch time as a JsonResponse and do the datetime conversion in my javascript AJAX call (i'm using charts.js to visualise the data). any pointers? code for reference: views.py def charts(request): # pie chart for payment type dow_queryset = Member.objects.order_by('member_created_time').values_list( 'member_created_time', flat=True) # return only the created time w/o key dow_queryset = list(dow_queryset) # list is the only native data type i can convert to successfully dow_queryset = float(dow_queryset) # this just .. … -
Using django model data in a bootstrap template
I'm attempting to create an expanding list displaying elements of a model that I have in django, but I'm having trouble getting the bootstrap 5 collapse function to work with the data from django. I'm relatively new to both, getting back into coding after an extended break. The code works if I replace id="{{saga.name}} with id="placeholder" and href="#{{ saga.name }}" with href="#placeholder", but refuses to do anything with the code as is. Is there something going on with how bootstrap 5 interprets the data? I feel like I'm going crazy here. {% for saga in sagaMemberList %} <a href="{{ saga.get_absolute_url }}">{{ saga.name }}</a> <a class="btn btn-primary" data-toggle="collapse" href="#{{ saga.name }}" role="button" aria-expanded="false" aria-controls="collapse{{ saga.name }}">dropdown</a> <div class="collapse" id="{{ saga.name }}"> {% for character in mSagaCharacterList|get_item:saga %} <div class="row"><div class="col"> <a href="{{ character.get_absolute_url }}">{{ character.name }}</a> </div></div> {% endfor %} </div> <br> {% endfor %} I'm know it's not the prettiest code and I'm sure it's inefficient as hell, but I'm really struggling to understand why it's not working. Thanks for any insight any of you might have. -
remove migrations files in Django
I have a Django project and I want to delete all migrations files inside the project with python. I did that with those commands, but I want to remove them with python. find . -path "*/migrations/*.py" -not -name "__init__.py" -delete find . -path "*/migrations/*.pyc" -delete -
In mpld3 how to make draggable line using mouse pointer?
I am trying to drag red vertical line in vertical direction towards right and left side using mouse pointer and on release I want to print x-axes value. I am not able to connect line_a with DragPlugin class. I followed https://mpld3.github.io/examples/drag_points.html this code as a reference. """ Draggable Points Example ======================== This example shows how a D3 plugin can be created to make plot elements draggable. A stopPropagation command is used to allow the drag behavior and pan/zoom behavior to work in tandem. """ import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import mpld3 from matplotlib import lines from mpld3 import plugins, utils class DragPlugin(plugins.PluginBase): JAVASCRIPT = r""" mpld3.register_plugin("drag", DragPlugin); DragPlugin.prototype = Object.create(mpld3.Plugin.prototype); DragPlugin.prototype.constructor = DragPlugin; DragPlugin.prototype.requiredProps = ["id"]; DragPlugin.prototype.defaultProps = {} function DragPlugin(fig, props){ mpld3.Plugin.call(this, fig, props); mpld3.insert_css("#" + fig.figid + " path.dragging", {"fill-opacity": "1.0 !important", "stroke-opacity": "1.0 !important"}); }; DragPlugin.prototype.draw = function(){ var obj = mpld3.get_element(this.props.id); var drag = d3.drag() .on("drag", dragged) obj.elements() .data(obj.offsets) .style("cursor", "default") .call(drag); function dragstarted(d) { d3.event.sourceEvent.stopPropagation(); d3.select(this).classed("dragging", true); } function dragged(d, i) { d[0] = obj.ax.x.invert(d3.event.x); d[1] = obj.ax.y.invert(d3.event.y); d3.select(this) .attr("transform", "translate(" + [d3.event.x,d3.event.y] + ")"); } function dragended(d) { d3.select(this).classed("dragging", false); } } """ def __init__(self, points): if … -
Select This button in HTML
I am building a BlogApp and I am working in a Image Cropping Feature AND i am stuck on a Problem. What i am trying to do :- There's a Image Cropping Feature in Create BlogPost page. AND when user fill all the details then user selects a image from Directory and crop it and THEN The Problem Is, There are two buttons in Image Cropping Section Back and Crop and Upload button. AND When user clicks on Back then it return to the Create Blog page without selected the image( which is good ) BUT when it click on Crop and Upload then blog is saving without return to Create Blog page and I want a button of Select this Image , So when user clicks on button then it will return in Create Post Section with the selected image. BUT i don't know how can i do it. What have i tried I have tried <input type="submit" value="okay" /> BUT it didn't work for me. I have also tried ` tag, BUT it also didn't work for me. create_post.html <div class="modal fade" id="modalCrop"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 … -
Django - print query result to html
I need some help with Django please. I am working on a questionnaire. I made a raw query where I made a summation with two cells of the same row. I can't find the method to print it to my HTML. views.py def query(request): my_query = Stressz_teszt.objects.raw('SELECT ID, stressz_v05 + stressz_v06 FROM stressz_stressz_teszt') context = { 'my_query': my_query, } return render(request, 'stressz/query.html', context) query.html {{ my_query }} {% for i in my_query %} {{ i.stressz_company }} --- {{ user }} --- {{ summation here !!! }} {% endfor %} Thank you for you reply in advance! -
Django admin error ValidationError: ['ManagementForm data is missing or has been tampered with'] due to conditional inline use
I have a custom User model(AbstractUser) and a Stock model. Assume there's multiple user roles manager, supplier etc. The manager can be able to view other manager's details and supplier details. The User model got a conditional inline which shows the stocks of each supplier if the user role is equalled to supplier.(Here role is a PositiveSmallIntegerField with choices and SUPPLIER = 2) class SupplierStockInline(admin.StackedInline): """ Inline to show stocks of a supplier """ model = Stock extra = 0 @admin.register(User) class UserAdmin(UserAdmin): """ User """ fieldsets = [ (None, {'fields': ('username', 'password')}), ('Personal info', {'fields': ( 'first_name', 'last_name', 'email', ... some custom fields... )}), ('Permissions', {'fields': ( 'is_active', 'is_staff', 'is_superuser', 'role', 'groups', 'user_permissions', )}), ('Important dates', {'fields': ('last_login', 'date_joined')}) ] list_display = [...] search_fields = [...] # --- the source of the problem --- inlines = [] def get_inlines(self, request, obj): """ Show inlines, stocks of supplier """ try: if obj.role == SUPPLIER: return [SupplierStockInline] except: pass return [] # --- ---- ----- This works just fine till I tried to change the role of a new user to supplier. ValidationError: ['ManagementForm data is missing or has been tampered with'] The issue is due to that overridden get_inlines() method. … -
Field 'id' expected a number but got 'Henry' (AJAX & DRF)
I am trying to get a user's list with an AJAX request and DRF. But get this error: Field 'id' expected a number but got 'Henry'. I'd be grateful for any assistance. AJAX: const showUserLists = function(map){ let userName = "Henry"; $.ajax({ type: 'GET', url: '/api/userlist/', data: { 'username': userName }, success: function (data) { data.forEach(item => { console.log(item.list_name) $("#userLists").append("<li class=userlist data-name=\"" + item.list_name + "\">" + item.list_name + "</li>") }) } }); }; urls.py: router = DefaultRouter() #need help understanding router register router.register('userlist', views.UserListViewSet, basename= 'userlist') views.py #this shows all lists for a user class UserListViewSet(viewsets.ModelViewSet): serializer_class = UserListSerializer def get_queryset(self): name = self.request.GET.get('username', None) return UserList.objects.filter(user=name) Serializer: class UserListSerializer(serializers.ModelSerializer): #this is what we worked on on October 1 class Meta: model = UserList fields = ['id', 'user', 'list_name'] class VenueListSerializer(serializers.ModelSerializer): created = serializers.ReadOnlyField() class Meta: model = VenueList fields = ['id', 'title'] Relevant model: class UserList(models.Model): list_name = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE) #is this okay? def __str__(self): return self.list_name Traceback Traceback (most recent call last): File "/Users/x/Desktop/Coding/anybody/avenv/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1774, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'Henry' The above exception was the direct cause of the following exception: Traceback (most recent call … -
Setting up React.js with Django failed
I am currently learning React.js and I followed some tutorial on Youtube for React.js basics. I didnt initially use npm run build(used it after im done coding frontend) and i created my react frontend app inside my django project. When I am running npm start on cmd, react app works perfectly fine on localhost:3000. enter image description here But after I tried to run npm run build and done setting up, STATICFILES_DIRS, template_dirs, STATIC_URL and such, when I runserver on port:8000 which is default for django, all I can see is a white screen, I included console on the screenshot for error references: empty django page with console I even tried to put some text inside the body 'frontend/build/index.html' just to see if django can access the template dirs, and the text put in shown on django homepage localhost:8000. -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/products/asa/ Raised by: products.views.ProductDetailSlugView Error
i've tried almost everything,can't figure out whats going on?! i think "try" logic is correct in ProductDetailSlugView, im using Django verson 2.2, in main url i have include, everything is working until SlugView and i have no idea whats happening :( i did researches almost everywhere, i tink im missing something i don't know products/views.py from django.http import Http404 from django.views.generic import ListView, DetailView from django.shortcuts import render, get_object_or_404 from .models import Product class ProductListView(ListView): template_name = "products/list.html" # def get_context_data(self, *args, **kwargs): # context = super(ProductListView, self).get_context_data(*args, **kwargs) # print(context) # return context def get_queryset(self, *args, **kwargs): request = self.request return Product.objects.all() def product_list_view(request): queryset = Product.objects.all() context = { 'object_list': queryset } return render(request, "products/list.html", context) class ProductDetailSlugView(DetailView): queryset = Product.objects.all() template_name = "products/detail.html" def get_context_data(self, *args, **kwargs): context = super(ProductDetailSlugView, self).get_context_data(*args, **kwargs) return context def get_object(self, *args, **kwargs): request = self.request slug = self.kwargs.get('slug') try: instance = Product.objects.get(slug=slug, active=True) except Product.DoesNotExist: raise Http404("Not found..") except Product.MultipleObjectsReturned: qs = Product.objects.filter(slug=slug, active=True) instance = qs.first() except: raise Http404("Error") return instance class ProductDetailView(DetailView): #queryset = Product.objects.all() template_name = "products/detail.html" def get_context_data(self, *args, **kwargs): context = super(ProductDetailView, self).get_context_data(*args, **kwargs) print(context) # context['abc'] = 123 return context def get_object(self, *args, **kwargs): request …