Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When adding a new member to an existing Enum class used by a Model field, is a new Django migration necessary?
Let's say I have a model Pie, and I add a field flavor, which is an EnumTextField. class FlavorType(Enum): APPLE = 'apple' BANANA = 'banana' Django auto-generates the migration: operations = [ migrations.AddField( model_name='pie', name='flavor', field=django_apps.core.fields.EnumTextField( choices=[(django_apps.bakery.constants.FlavorType('apple'), 'apple'), (django_apps.bakery.constants.FlavorType('banana'), 'banana')], enum_cls=django_apps.bakery.constants.FlavorType ), ), ] Let's say that later on, I add a new member, such as FlavorType.CHERRY: class FlavorType(Enum): APPLE = 'apple' BANANA = 'banana' CHERRY = 'cherry' Question: Does a new AlterField migration need to be made to update field.choices? My guess is no, because we've already specified the enum_cls. I notice that makemigrations doesn't create a new migration file when this enum member is added. Additionally, I can save a new pie of flavor cherry to the database with no problem. If this is the case, then 1) I find it a little misleading that choices is even in the original migration and 2) I couldn't find any documentation about it. Any insight is appreciated! -
django: Javascript pop up alert not working
I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is grabbing the info from the values and setting up a Javascript alert to show which boxes were selected. And to add up all the corresponding prices of each value, and displaying it. views.py def inventory(request): products = request.POST.getlist('products') for product in products: a = Post.objects.get(title=product) a.quantity = a.quantity -1 a.save() print(products) return redirect('blog-home') home.html {% extends "blog/base.html" %} {% block content %} <form action="{% url 'js' %}" method="POST" id="menuForm"> {% for post in posts %} {% if post.quantity > 0 %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.category }}</a> </div> <h2><a class="article-title" >{{ post.title }}</a></h2> <p class="article-content"> Price: ${{ post.Price }}</p> <p class="article-content"> Sale: ${{ post.Sale }}</p> <input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }} </input> </div> </article> {% else %} {% endif %} {% endfor %} <button type="submit" form="menuForm">Confirm Purchase</button> </form> {% endblock … -
Exporting user to db followed by creating subscription object throws the error 'User' object is not iterable'
I am exporting data to db using the following code, now I want to create subscription also to be created for uploaded users. Export part is working, but subscription throw the above error. def user_upload(request): template = "client_admin/user_upload.html" csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar="|"): if len(column) > 9: try: users = User( username=column[0], first_name=column[1], last_name=column[2], email=column[3], add_1=column[4], add_2=column[5], suburb=column[6], state=column[7], postcode=column[8], country=column[9], ) users.set_password('password') users.save() pricing = Pricing.objects.get(name='Free Trial') for user in users: subscription = Subscription.objects.create(user=user, pricing=pricing) stripe_customer = stripe.Customer.create( email=user.email ) stripe_subscription = stripe.Subscription.create( customer=stripe_customer["id"], items=[{'price': 'price_1HkPckwjpOS8'}], trial_period_days=7 ) subscription.status = stripe_subscription["status"] subscription.stripe_subscription_id = stripe_subscription["id"] subscription.save() except IntegrityError as e: return render_to_response('snippets/message.html') context = {} How I can get the list of just uploaded users and loop through it to create subscription object, any help will be appreciated. -
On django heroku deployment with postgres database getting error: DATABASES is improperly configured. Please supply the NAME value
Hi I am new to Heroku and I am trying to deploy my django app on the site. The issue I am running into is in the title. It seems to have an issue connecting to my postgres database. In my local environment, the database works perfectly fine this issue only seems to come up with the heroku deployment. I have added the DATABASE_URL already as a config var on Heroku. The app deploys but just says Internal Server Error, Here is the error logs heroku is giving me: raise ImproperlyConfigured( 2020-12-14T23:41:58.543920+00:00 app[web.1]: django.core.exceptions.ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. 2020-12-14T23:41:58.544131+00:00 app[web.1]: 10.148.121.8 - - [14/Dec/2020:23:41:58 +0000] "GET / HTTP/1.1" 500 0 "-" "-" 2020-12-14T23:41:58.545021+00:00 heroku[router]: at=info method=GET path="/" host=premtablelive.herokuapp.com request_id=aa3e9556-0490-4690-8b0b-d414e69a0305 fwd="24.190.19.51" dyno=web.1 connect=1ms service=5ms status=500 bytes=244 protocol=https I'm not sure what is causing this issue I am not spelling the name value for my database wrong in my code as it works in my local environment. here is my settings: from pathlib import Path import django_heroku import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: … -
Error: Request Entity Too Large, Your client issued a request that was too large
I am using google cloud engine to run django application and cloud storage to save media files. Looks like I can save files upto 2 Mega Bytes. But if I try to save large file I get this error Error: Request Entity Too Large, Your client issued a request that was too large. I am using django-storages library to save files to google cloud. This is how I save it from django.core.files.storage import default_storage obj.file.save('file_name', ContentFile('more content')) In my settings.py file I played with GS_BLOB_CHUNK_SIZE = 256K as explained here. Though it takes time to save, but works on my local server, but doesn't on cloud engine. Any help on this issue is much appreciated. -
{"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}
I keep getting the {"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"} error. I print the json it's receiving and it seems correct {'order_package': {'package': 1, 'package_quantity': 1}} Here's all the code I think is related. The post method: @permission_classes((AllowAny,)) def post(self, request): print(request.data) data = JSONParser().parse(request) serializer = serializers.CartSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=200) else: return Response.status_code(500) Cart model: class Cart(models.Model): order_package = models.ForeignKey(OrderPackage, on_delete=models.CASCADE, null=True, blank=True) order_item = models.ForeignKey(OrderItem, on_delete=models.CASCADE, null=True, blank=True) and the order package: class OrderPackage(models.Model): package = models.ForeignKey(Package, on_delete=models.CASCADE) package_quantity = models.IntegerField() I also tried not using json parser and passing request.data right into the data= in the serializer which gives the same error. Any help is appreciated. -
Django: Why won't my video display in template? (Error "No video with supported format and MIME type found")
I have a page in which a user can do several things and that should display a video the user uploaded, but I get this error ("No video with supported format and MIME type found"), even though—I think—I am doing exactly what I have found online in several places. These are my MEDIA_ROOT and MEDIA_URL in settings.py: MEDIA_URL = 'media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Inside the media directory, I have subdirectories for each user, which are created—if they don't exist already—when a user creates a project and uploads a video. Inside the user subdirectories, there is one directory for each project the user creates. Inside these, several files exist, including the video. So, for the test I'm doing right now, this is the structure: |— media |— user_3 |— Test_project |— video_file.mp4 |— irrelevant_file |— irrelevant _file ... The video is a FileField in a model I called Project. In my view, I get the video url and pass it to the template in the following way: (I am omitting any part of the code that is irrelevant to this issue) def sample_view(request, project_id): video = Project.objects.get(pk=project_id).video_file.url # ... some irrelevant code # The formset has always worked. I am … -
problem with celery state when launching several tasks together
I have a celery task to upload videos to a server. It goes like this: x=asynchronousupload.delay(idcf,i,info['recording_files'][ijk]['download_url']+"?access_token="+utils.generateToken(),uuids,tit,descr,who,info['recording_files'][ijk]['recording_start'],info['recording_files'][ijk]['recording_end']) I call that for 10 videos in parallel. I store the task numbers and then I'm able to check periodically the state of each task doing like so: res = AsyncResult(taskid[ij]) res.ready() res.state The problem is that all tasks succeed (I see that the videos are uploaded where I want and the task functions execute themselves and return the right value) but it is only one task that returns SUCCESS in res.state. When this one task (I suppose the first one that finished) is finished I then stop everything and load the page but sometimes it is just too early and not everything is finished. I'd like to get the other tasks to show SUCCESS as well but even though I wait (and they executed everything they had to and returned the right value), it never ends up SUCCESS and remains PENDING. What is happening? -
POSTMAN -> DJANGO -- Upload Binary file (jpeg). Can't get it to work no matter what I do
to simplify: curl --location --request PUT 'https://myserver.com/upload' \ --form 'file=@/Users/myname/Desktop/bond.jpg' \ --form 'test=test' It gets to my Django App: class MyUploadView(APIView): parser_classes = [FormParser, MultiPartParser] def put(self, request, **kwargs): print(request.FILES) but gives out: <MultiValueDict: {}> nothing I do work, file is always empty. when I use Content-Type: multipart/form-data it doesn't work as well, and sometimes django would complain there is no boundary -- but any value there gives out the same error. MY GOAL IS SIMPLE: all I want it to upload a file to django and save it to disk on the backend. I cannot believe this i taking all day long with zero results and zero examples online that actually work. -
Django images don't fill height
I am currently working on a django blog. However, I am experiencing some difficulties with the size of the post thumbnails. Here's a picture: What I marked in yellow is how the image should be filling the space. The width is fine, but the heigh isn't working well as you can see. Here's the code: {% extends 'base.html' %} {% load static %} {% block content %} <style> img { height: 100%; width: 100%; } </style> <!-- Post--> {% for obj in object_list %} <div class="row d-flex align-items-stretch"> {% if not forloop.first and not forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the image {% endif %} <div class="text col-lg-7"> <div class="text-inner d-flex align-items-center"> <div class="content"> <header class="post-header"> <div class="category"> {% for cat in obj.categories.all %} <a href="#">{{ cat }}</a> {% endfor %} </div> <a href="{{ obj.get_absolute_url }}"> <h2 class="h4">{{ obj.title }}</h2> </a> </header> <p>{{ obj.overview|linebreaks|truncatechars:200 }}</p> <footer class="post-footer d-flex align-items-center"><a href="#" class="author d-flex align-items-center flex-wrap"> <div class="avatar"><img src="{{ obj.author.profile_picture.url }}" alt="..." class="img-fluid"></div> <div class="title"><span>{{ obj.author }}</span></div></a> <div class="date"><i class="icon-clock"></i> {{ obj.timestamp|timesince }} ago</div> <div class="comments"><i class="icon-comment"></i>{{ obj.comment_count }}</div> </footer> </div> </div> </div> {% if forloop.first or forloop.last %} <div class="image col-lg-5"><img src="{{ obj.thumbnail.url }}" alt="..."></div> #Here's the … -
Django Channels JWT Authentication
I'm trying to access the user in the scope in my Consumer.py and grab some user related models from the DB. However, it seems like AuthMiddlewareStack I'm using for authenticating all the websocket connections is not working correctly. What is the best/secure way to be able to authenticate websocket connection in django channels when I'm using JWT Tokens django-rest-framework-simplejwt for authentication in my REST Framework? -
Render a form inside a modal - django
Probably my question is easy enough for people more experienced than me, so i would like your help with the following. I would like to use a modal on my website for Login/Register and i have an issue when rendering a form inside the modal. I've created a urls.py file app_name = "users" urlpatterns = [ path('register/', UserRegisterView.as_view(), name='register') ] the views.py file where loading the AccountRegisterForm class UserRegisterView(SuccessMessageMixin, CreateView): template_name = 'users/register.html' form_class = AccountRegisterForm success_url = '/' success_message = "Your account has been created!" the template <li class="list-inline-item list_s"><a href="#" class="btn flaticon-user" data-toggle="modal" data-target=".bd-example-modal-lg"> <span class="dn-lg">Login/Register</span></a></li> </ul> </nav> </div> </header> <!-- Modal --> <div class="sign_up_modal modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <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> </div> <div class="modal-body container pb20"> <div class="row"> <div class="col-lg-12"> <ul class="sign_up_tab nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Login</a> </li> <li class="nav-item"> <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Register</a> </li> </ul> </div> </div> and the form: <form method="POST" form action="{% url 'users:register' %}"> {% csrf_token %} <div class="row"> <div class="col-lg-12"> <button type="submit" class="btn btn-block btn-fb"><i class="fa fa-facebook float-left mt5"></i> Login with Facebook</button> </div> <div class="col-lg-12"> … -
Django logging errors occuring in admin page
I face the following issue: I want to add a new instance of a model in the django admin page, but I do get an 500 error. Now I want to log all the errors occurring in the admin page to a file. Important details: website running in production, hence I do not get feedback in the browser or the console (since I use Gunicorn). this occurs only for one specific model. this only happens when adding a new instance for that model, not when changing exisiting instance logging in the view does not help, since error occurs within admin page I do not want you to help me debug my django code. I am only interessted for tips and a tutorial on how to log every error occuring no matter if it happens in the admin page or the actual site. I am happy for any tips and suggestions! Thanks! Thanks for any advice! -
Django-reactjs Not Found: /asset-manifest.json
I'm trying to connect my ReactApp to my Django server. I actually did connect these 2 but I can't get the layout of react app on the django side.However, I can see the title of ReactApp on my Django server but no layout at all, actually there is nothing but white page at localhost:8000(django-server). If I check my django server from my terminal I get this following Not Found: /manifest.json I actually do have a manifest.json in my react app. I can send screenshots, or more code If you ask. -
how to save step for FormWizard Django
I have a series of related models and I need to save the queryset in the current step to be available in the next step, otherwise a choice option will be empty forms.py class AttachmentForm(forms.ModelForm): class Meta: model = Attachment fields = '__all__' class SkuAttachmentForm(forms.ModelForm): class Meta: model = SkuAttachment fields = '__all__' class DomainsAttachmentForm(forms.ModelForm): class Meta: model = DomainsAttachment fields = '__all__' widgets = { 'name_key': forms.TextInput(attrs={'disabled': True}), } def __init__(self, *args, **kwargs): # first call parent's constructor super(DomainsAttachmentForm, self).__init__(*args, **kwargs) # there's a `fields` property now self.fields['name_key'].required = False models.py class DomainsAttachment(models.Model): name_key = models.CharField(default='frequency', max_length=100) values_allow = models.CharField(verbose_name='Frequencia', help_text='1month ou 1, 15, 28', max_length=50) class Attachment(models.Model): name = models.CharField(max_length=50) is_required = models.BooleanField(default=False) is_active = models.BooleanField(default=True) domains = models.ManyToManyField(DomainsAttachment) class SkuAttachment(models.Model): attachment = models.ForeignKey(Attachment, on_delete=models.CASCADE) sku = models.ForeignKey(Sku, on_delete=models.CASCADE) -
PWA serviceworker.js being displayed on startup of website
When I open up my website when it is first deployed, the javascript code of the serviceworker is displayed on a white screen instead of the website and I have to hard refresh the page everytime to make it work. I don't know why its doing this. I am using Django as my backend so my manifest.json is in the settings.py file. Here is my serviceworker code: var staticCacheName = 'djangopwa-v1'; self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '', ]); }) ); }); self.addEventListener('fetch', function(event) { var requestUrl = new URL(event.request.url); if (requestUrl.origin === location.origin) { if ((requestUrl.pathname === '/')) { event.respondWith(caches.match('')); return; } } event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); Here is my manifest code: #PWA manifest.json settings PWA_APP_NAME = 'test' PWA_APP_DESCRIPTION = "test PWA" PWA_APP_THEME_COLOR = '#000000' PWA_APP_BACKGROUND_COLOR = '#ffffff' PWA_APP_DISPLAY = 'standalone' PWA_APP_SCOPE = '/' PWA_APP_ORIENTATION = 'any' PWA_APP_START_URL = '/' PWA_APP_STATUS_BAR_COLOR = 'default' PWA_APP_ICONS = [ { 'src': 'static/images/icon-160x160.png', 'sizes': '160x160' } ] PWA_APP_ICONS_APPLE = [ { 'src': 'static/images/icon-160x160.png', 'sizes': '160x160' } ] PWA_APP_SPLASH_SCREEN = [ { 'src': 'static/images/icon.png', 'media': '(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)' } ] PWA_APP_DIR = 'ltr' PWA_APP_LANG = 'en-US' -
Custom Django Form - modify cleaned data based on request
This has most likely already been asked before, but I could not figure out the right thing to google. I am creating a simple form for people to fill out a COVID screen for an event. Basically, they click on an event and then click fill out form. I have created a model for this as such: class Response(models.Model): """ model for a completed covid screen """ temperature = models.DecimalField(max_digits=5, decimal_places=2, default=98.6) contact_with_covid = models.BooleanField(default=False) account = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) time = models.DateTimeField() event = models.ForeignKey("Event", on_delete=models.CASCADE) def __str__(self): return f'{self.account.user.username}\'s response for "{self.event.title}"' As well as created a form for users to fill out for this response. class ResponseForm(forms.ModelForm): class Meta: model = Response fields = ['temperature', 'contact_with_covid'] labels = {'contact_with_covid': 'Have you had contact with covid in the last 14 days?'} help_texts = {'temperature': 'Your temperature in degrees.'} I did not want the user to select the account, time and event parameters. They should be defined as such: account should be the currently logged in user request.user.account time should be the time of submission datetime.datetime.now() event should be the event in the URL parameter. path('event/<uuid:event>/response/create', views.create_response, name='response-create') Therefore, the view I have sets these parameters in cleaned_data after … -
I need help in Filter some data id Django
I have a model structure, but have tough time understanding how to use the Django filters. models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) class Bar(models.Model): user_id = models.OneToOneField(User, on_delete=models.CASCADE) name = models.CharField(max_length=10) class Tables(models.Model): bar = models.ForeignKey(to=Bar, on_delete=models.CASCADE) I want to be able to filter the user of a table from the model below. -
CART functionallity in DRF
I am new to Django and currently setting up an ecommerce backend. I have created models, serializers, views and urls. Now, I need to set up a cart functionality, like create/update/delete/calculate_total and etc. The thing is I am totally lost. Don't know where to start and what to do next. If you have a little time for quick guidance I'd be sincerely grateful. class Cart(models.Model): owner = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) number_of_items = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) def __str__(self): return "User: {}, items in cart: {}".format(self.owner, self.number_of_items) class CartItem(models.Model): cart = models.ForeignKey(Cart, on_delete=models.CASCADE, default=None) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.PositiveIntegerField() def __str__(self): return str(self.id) class CartSerializer(serializers.ModelSerializer): owner = serializers.StringRelatedField() class Meta: model = Cart fields = '__all__' class CartItemSerializer(serializers.ModelSerializer): class Meta: model = CartItem fields = "__all__" class CartView(viewsets.ModelViewSet): serializer_class = CartSerializer queryset = Cart.objects.filter() def perform_create(self, serializer): serializer.save(owner=self.request.user) class CartItemView(viewsets.ModelViewSet): serializer_class = CartItemSerializer queryset = CartItem.objects.all() router = DefaultRouter() router.register(r'view', CartView) router.register(r'item', CartItemView) urlpatterns = [ path('', include(router.urls)), ] -
Django unable to iterate prefetch_related objects at template
I'm unable to access my prefetch_related objects at my template, can smb help views.py def support(request, pk=None): ... else: list_support_tickets = sorted( chain( SupportTickets.objects.filter(Q(status=0) | Q(status=1), requester=request.user).prefetch_related('reply_relation'), #Can't iter object ), key=attrgetter('creation_date'), reverse=True ) paginator = Paginator(list_support_tickets, 10) page = request.GET.get('page') support_tickets = paginator.get_page(page) args = {'support_tickets': support_tickets, 'form': form } print(list_support_tickets) return render(request, template, args) At my template I do the following: {% for support_ticket in support_tickets %} ... {% for reply in support_ticket.reply_relation %} <span class="font-size-small">We have a query, yeah</span> {% endfor %} {% endfor %} But I'm unable get a query here, error: TypeError: 'GenericRelatedObjectManager' object is not iterable models.py class SupportTicketMessages(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to=referential_models, on_delete=models.CASCADE) object_id = models.CharField(max_length=36) content_object = GenericForeignKey('content_type', 'object_id') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='support_ticket_reply_author', verbose_name='Author', blank=True) reply = models.TextField(verbose_name="Reply Content", max_length=2000) date = models.DateTimeField(auto_now_add=True, blank=False) class SupportTickets(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) ticket_id = models.IntegerField(default=ticket_id_generator, unique=True, blank=False, null=False, editable=False) requester = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) category = models.IntegerField(choices=TICKET_CATEGORY, verbose_name='Ticket Category') subject = models.CharField(max_length=40) problem_description = models.TextField(max_length=5000) status = models.IntegerField(choices=STATUS_OF_TICKET, verbose_name='Ticket Status', default=0) reply_relation = GenericRelation(SupportTicketMessages, related_query_name='reply_relation') creation_date = models.DateTimeField(auto_now_add=True, null=True) Thanks in advance -
How can I filter objects in my model to only show those of my ForeignKey user?
Trying to filter objects in my view.py to only show items (in my case Buckets) owned by Users. I implemented the code below in my original Model [my model.py code is at the bottom of post] class PostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Bucket.owner) But I'm not sure if that is the correct procedure to list all items? Here is the view.py where I'm trying to filter data by User aka owner. Users should ONLY be allowed to view their own items. (I will deal with permissions later) class BucketList(generics.ListCreateAPIView): queryset = Bucket.objects.all() #INSERT FILTER HERE pass Here is the model I'm referring too. class Bucket(models.Model): options = ( ('personal', 'Personal'), ('social', 'Social'), ) class PostObjects(models.Manager): def get_queryset(self): return super().get_queryset().filter(status=Bucket.owner) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='buckets') users = models.ManyToManyField(settings.AUTH_USER_MODEL) category = models.CharField(max_length=30, choices=options) name = models.CharField(max_length=35) created = models.DateTimeField(default=timezone.now) slug = models.SlugField(unique=True, blank=True) stock_count = models.IntegerField(blank=True, null=True) stock_list = ArrayField(models.CharField(max_length=6),size=10) objects = models.Manager() postobjects = PostObjects() class Meta: ordering = ('-created',) def total_stocks_calc(self): self.stock_count = Bucket.objects.aggregate(Sum('stock_list', distinct=True)) self.save() def get_absolute_url(self): return reverse("bucket:bucket-view", kwargs={"slug": self.slug}) def __str__(self): return self.stock_list To re-state my question, how can I filter objects owned by users in class BucketList for their private view only? UPDATE: from django.db.models import Q … -
Django custom user model with password
Can Django use a password field from a legacy db for authentication? I have got all of my models working with my legacy postgresql database. I have implemented the custom user model as documented and switched the login to USERNAME_FIELD = 'email'. When running createsuperuser, I do not get prompted for password. I would like to use the password field in my legacy postgres db, field name crypted_password. During createsuperuser I get an error after entering the email. django.db.utils.ProgrammingError: column accounts_users.password does not exist LINE 1: SELECT "accounts_users"."id", "accounts_users"."password", "... I am not sure what info would be useful for assistance. I have implemented the custom user model step by step as documented in official documentation. I am at a loss. -
IntegrityError: FOREIGN KEY constraint failed
I am trying to post a form(ReviewForm) but I get the error FOREIGN KEY constraint failed when my form tries to save.Any help please?Thanks in advance. Here is my views.py code(the post function in the view class) def post(self,request,*args,**kwargs): pk=self.kwargs.get("pk") di = self.kwargs.get("di") dis=get_object_or_404(Disease,pk=di) pestiside=Pestiside.objects.get(pk=pk,disease=dis) if request.method=='POST': user = request.user form= ReviewForm(request.POST) if form.is_valid(): form.save() comment=form.cleaned_data.get('comment') new_review=Review.objects.create(author=user,pes_id=pestiside_id,comment=comment) new_review.save() return redirect('diagnose:pestiside') Here is my models.py code: class Review(models.Model): author= models.ForeignKey(User,default=1, on_delete=models.CASCADE) time = models.DateTimeField(auto_now_add=True, blank=True) pes = models.ForeignKey(Pestiside,default=0,on_delete=models.CASCADE) comment = models.CharField(max_length=200) Here is my forms.py code: class ReviewForm(forms.ModelForm): class Meta: model=Review fields=('comment',) Here is my stacktrace,the error shows at form.save() in views.py : Traceback (most recent call last): File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute return Database.Cursor.execute(self, query, params) The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception: File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/views/generic/base.py", line 97, in dispatch return handler(request, *args, **kwargs) ***File "/home/risper/django_projects/Tomadoc/diagnose/views.py", line 276, in post form.save()*** File "/home/risper/django_projects/env01/lib/python3.6/site-packages/django/forms/models.py", … -
Django: Setting a cookie asynchronously
To set a cookie, I used this on Django docs.. blog/models.py class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=180, null=False) text = tinymce.models.HTMLField() created_date = models.DateTimeField(auto_now_add=True, editable=False) published_date = models.DateTimeField(null=True, default=None) def __str__(self): return self.title def publish(self): self.published_date = timezone.now() self.save() class Like(models.Model): post = models.ForeignKey(Post, on_delete=models.DO_NOTHING) liked = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, editable=True) visitor_uid = models.CharField(max_length=37) def __str__(self): return self.visitor_uid[:5] blog/views.py import uuid def make_cookie(request, pk): post = get_object_or_404(Post, pk=pk) like = Like() like.post = post like.visitor_uid = str(make_uuid()) like.save() request.session[post.pk] = like.visitor_uid Making a HttpResponse('Some HTML') which redirects. I don't want this behaviour to happen without the refreshing/redirecting. Also referred this from GFG but even they are redirecting... Any ideas? -
Django can't resolve url path 404
Hi I'm having a very annoying issue with django: I've setup many urls paths and they all work fine except one and I really can't figure out why: Urls urlpatterns = [ # path('foods/search', food_search), path('food_list/', FoodListVersionListCreateAPIView.as_view(), name='foodList-list'), path('all_foods/<str:survey>/<str:string>', FoodListCreateAPIView.as_view(), name='food-list'), path('food_classification/', FoodClassificationListCreateAPIView.as_view(), name='foodClassification-list'), path('food/<str:survey>/<str:string>/', FoodDetailAPIView.as_view(), name='food-detail'), ] Views class FoodListCreateAPIView(generics.ListCreateAPIView): queryset = Food.objects.all() serializer_class = FoodSerializer filter_backends = [DjangoFilterBackend, filters.SearchFilter] filterset_fields = ['description', 'food_code', 'cofid_code', 'foodex_code', 'food_classification'] search_fields = ['food_list', 'SYSTEM_TIME'] permission_classes = [permissions.IsAuthenticatedOrReadOnly] def get_queryset(self): assert self.queryset is not None, ( "'%s' should either include a `queryset` attribute, " "or override the `get_queryset()` method." % self.__class__.__name__ ) survey = self.request.query_params['survey'] food = self.request.query_params['string'] raw_queryset = perform_food_search(survey, food) queryset = Food.objects.filter(pk__in=[i.pk for i in raw_queryset]) if isinstance(queryset, QuerySet): # Ensure queryset is re-evaluated on each request. queryset = queryset.all() return queryset Error message