Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Can I Get A Dictionary Value From Python?
I was trying to convert a look up today to a data dictionary...for performance reasons... It's almost working...Except that it's duplicating the entries on my output... Here is my code in question... class Calendar(HTMLCalendar): def __init__(self, year=None, month=None, user=None): self.user = user self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, requests): requests_per_day = DailyPlannerRequest.objects.filter(Q(created_by=self.user)).distinct().order_by('start_time') daily_planner_events1 = [] for requests in requests_per_day: requests_per_day_dict = model_to_dict(requests) daily_planner_events1.append(requests_per_day_dict) daily_planner_events1 = dict() events = add_event_dates(requests_per_day) all_event_dates = [] for event in events: for date in event.dates: if date not in all_event_dates and date.month == self.month and date.year == self.year: all_event_dates.append(date) for event in events: for date in event.dates: if date in all_event_dates and date not in daily_planner_events1 and date.month == self.month and date.year == self.year: daily_planner_events1[date] = [event] else: if date.month == self.month and date.year == self.year: daily_planner_events1[date].append(event) # daily_planner_events[date].append(events) d = '' for requests in requests_per_day: for event in daily_planner_events1: if event.day == day: d += f'<li> {requests.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' The code above works...Except it's giving me incorrect output...The problem piece in particular is this... for requests in … -
project() missing 1 required positional argument: 'pk'
am confuse right now...i want to pass in a key value but i kept on getting error my code urls from django.urls import URLPattern, path from . import views urlpatterns = [ path('', views.projects, name="projects"), path('project/', views.project, name="project"), ] and the function i created def project(request, pk): projectObj = None for i in projectslist: if i['id'] == pk: projectObj = i return render(request, 'projects/single-project.html', {'project': projectObj}) -
error: no such column: blog_marketreview.name even when i have a field named name
i get the error no such column: blog_marketreview.name even when i clearly have a field named name in my app blog and model marketreview. I HAVE done makemigrations and migrate but the error persists. here is my models.py class MarketReview(models.Model): post = models.ForeignKey(MarketPost, related_name="mreviews", on_delete=models.CASCADE) name = models.CharField(max_length=255) body = models.TextField() date_added = models.DateTimeField(auto_now_add=True) rate = models.PositiveSmallIntegerField(choices=RATE_CHOICES) def __str__(self): return '%s - %s' % (self.post.title, self.name) here is the marketpost model that i connect to using foreignkey: class MarketPost(models.Model): title = models.CharField(max_length=100) price = models.DecimalField(default=0, max_digits=9, decimal_places=2) post_image = models.ImageField(null=True, blank=False, upload_to='marketplace_images/') content = models.TextField() #content = RichTextField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title + ' | ' + str(self.author) def get_absolute_url(self): return reverse('marketplace-detail', args=(str(self.id))) and here the template that had an error during rendering: <hr> 27 <br><br> 28 29 {% if not post.mreviews.all %} 30 <h4>No reviews yet... Be the first one!</h4> 31 <a href="{% url 'add-marketreview' post.pk %}">Add a Review</a> 32 33 {% else %} 34 <a href="{% url 'add-marketreview' post.pk %}">Add a Review</a> 35 <br><br> 36 **{% for review in post.mreviews.all %} this line is in red** 37 <h4>{{ user.name }}</h4> 38 <b>{{ review.name }} - {{ review.date_added }}</b> 39 <br> … -
handling courses with multiple languages in database design
I have to handle courses available in multiple languages, and also keep track of the user progress for each language available class Language(models.Model): code = models.CharField(primary_key = True) name = models.CharField() class TextContent(models.Model): textId = models.UUIDField(default = uuid4, primary_key = True,editable = False) language = models.OneToOneField(Language) class OriginalText(models.Model): originalText = models.CharFIeld() language = models.ForeignKey(Language) class Product(models.Model): name = models.OneToOneField() title = models.OneToOneField(OriginalText) class Course(models.Model): languages = models.ManyToManyField(Language) class Chapter(models.Model): title = models.OneToOneField(OriginalText) ........... class Lesson(models.Model): title = models.OneToOneField(OrigianlText) class LessonContent(models.Model): lesson = models.ForeignKey(Lesson) language = models.ForeignKey(Language) textContent = models.TextField() videoContent = models.FielField() class CourseEnrollment(models.Model): course = models.ForeignKey(Course) user = models.ForeignKey(User) in LessonContent class I have textContent and videoContent fields that's because the lesson could be a video or simply an article I want to track the user's progress in terms of chapters and video time progress to continue if he got interrupted and specially that each lesson video can be different in length depending on the language, I am still struggling to find a way to achieve this class UserProgress(models.Model): ...... so is my way of handling multiple-language courses right and if anyone can help me with tracking the user progress any help would be really appreciated -
How to set User's password in django with async, or create User
i have telegram bot(aiogram) for django-site registration, and here is problem. Django have a lot of async methods but i didn't find method for setting user password. Main idea here, but with aupdate_or_create i can't set password. Maybe i need use async to sync or something like this. but I'm almost sure that it is easy to solve with async, but I don't know how user, is_created = await User.objects.aupdate_or_create( username=message.from_user.username, email=data['email'], ) await user.set_password(data['password']) user.save() -
django migrate: ValueError: too many values to unpack (expected 2)
i write this model in models.py from django.db import models class Article(models.Model): title = models.CharField(max_length=255) text = models.TextField() pub_date = models.DateField(auto_now_add=True) and i run python manage.py migrate and receive this error Operations to perform: Synchronize unmigrated apps: messages, staticfiles Apply all migrations: admin, auth, contenttypes, news, sessions Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying auth.0001_initial...Traceback (most recent call last): File "/home/ilya/code/Project1/app/manage.py", line 22, in <module> main() File "/home/ilya/code/Project1/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/core/management/base.py", line 96, in wrapped res = handle_func(*args, **kwargs) File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 349, in handle post_migrate_state = executor.migrate( File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 135, in migrate state = self._migrate_all_forwards( File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 167, in _migrate_all_forwards state = self.apply_migration( File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/db/migrations/executor.py", line 249, in apply_migration with self.connection.schema_editor( File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/schema.py", line 39, in __exit__ self.connection.check_constraints() File "/home/ilya/code/Project1/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 289, in check_constraints for column_name, ( ValueError: too many values to unpack (expected 2) ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ -
Django EmailMessage how to send html message
Good day,how can I send html when I use django EmailMessage from django.shortcuts import render, HttpResponse from django.core.mail import EmailMessage def send_email(request): msg = EmailMessage( subject='this is the title', body='this is the content', from_email='test@gmail.com', to=['anothertest@yahoo.com'] ) msg.attach_file('t2.xls') msg.send(fail_silently=False) return HttpResponse('OK') I tried html_message but still not work: msg = EmailMessage( subject='this is the title', body='this is the content', from_email='test@gmail.com', to=['anothertest@yahoo.com'] html_message = '<p>this is an automated message</p>' ) Any friend can help ?Thanks! -
Django overridden choices failing validation
I am overriding the choices option defined in the model, which is just a blank tuple. Here's my models.py #For assigning Ciena loopbacks class Dia_Address(models.Model): order_reference = models.ForeignKey(Order, null=True, on_delete=models.CASCADE) equipment_hostname = models.CharField(max_length=500, null=True, verbose_name="Equipment Hostname", help_text="Hostname of the DIA device.") subnet = models.CharField(max_length=200, null=True, choices=DIA_SUBNETS, help_text="Subnet in which the DIA device requires an address.") Contents of my forms.py, which overrides the model choices. class Dia_AddressForm(ModelForm): class Meta: model = Dia_Address fields = ['equipment_hostname', 'subnet'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) #order_id = str(order_reference.id) dcn_address_handler = AddressHandler subnet_id = "94806" DIA_SUBNETS = () NEW_SUBNETS = dcn_address_handler.get_subnet_data(dcn_address_handler, subnet_id) DIA_SUBNETS = NEW_SUBNETS + DIA_SUBNETS self.fields['subnet'].choices = DIA_SUBNETS Contents of my views.py def addDia_Address(request, pk_test): order = Order.objects.get(id=pk_test) dia_address_form = Dia_AddressForm() if request.method == 'POST': dia_address_form = Dia_AddressForm(request.POST) dia_address_form.instance.order_reference = order if dia_address_form.is_valid(): dia_address_form.save() return redirect('order', pk_test) context = {'dia_address_form':dia_address_form} return render(request, 'orchestration/dia_address_form.html', context) The issue I have is this form is failing validation. I am able to select the appropriate option from the form dropdown menu. Is there any way I can disable this validation for just this one charfield? -
Printing out the event sent to a websocket but receiving received: {"isTrusted":true} as opposed to text received
I have a websocket that listens for a connection and sends data from my frontend to my websocket. I expect my websocket to send back a message indicating that it has received said data and my terminal to print out the text send. However, I am getting this: received: {"isTrusted":true} This is what I am sending: const testData = ['spill','test'] This is the receive function from my server: class PracticeConsumer(AsyncConsumer): ... async def websocket_receive(self, event): print("received:", event["text"]) sleep(1) await self.send({"type": "websocket.send", "text": event["text"]}) ... -
how to add custom templates in django-ckeditor in django
I am trying to use the Templates feature of the CKEditor in Django and I want to add some custom templates in the list. I've used this approach. I've tried editing myvenv\Lib\site-packages\ckeditor\static\ckeditor\ckeditor\plugins\templates\templates\default.js default.js CKEDITOR.addTemplates("default",{imagesPath:CKEDITOR.getUrl(CKEDITOR.plugins.getPath("templates")+"templates/images/"),templates:[{title:"Welcome Template",image:"template2.gif",description:"A template that you can send to clients as a welcome message.",html:' <h2>Welcome</h2> <p>Hi, <strong> Name here </strong> </p><p>You have recently shown an interest . . . </p>'},]}); but it didn't help, I've tried the collect static command but it didn't help either. I am still seeing the same default three templates. I'm not sure but there is another option of using extra plugins in the settings.py file but I don't know how to use it for this problem. settings.py CKEDITOR_UPLOAD_PATH = "file_upload/" CKEDITOR_CONFIGS = { 'default': { 'toolbar':'full', }, } apps INSTALLED_APPS = [ ..., 'ckeditor', 'ckeditor_uploader', ] urls.py urlpatterns = [ path('ckeditor/',include('ckeditor_uploader.urls')),] models.py class text(models.Model): body = RichTextField(blank=True, default="None") So my question is how to add custom templates in django-ckeditor==6.3.2? -
Using django modeling, how do you properly extend a model?
I'm an amateur developer who has been learning python in order to build my first full-stack project, which is an animal exchange site for a game I play. The animals can have up to 3 traits, but some of them have special ones. In the case of animals with special traits, I attempted to extend the base model and add additional traits using a notation someone suggested, but it doesn't seem to work. I know that technically I can just copypaste the base trait set and manually add them in, with a different model every time but that seems like it would bloat my code, and I'd like to be efficient about it. If you notice something else that could be improved, please let me know, thanks. from django.db import models #traits listed in class animal are base traits class ANIMAL(models.Model): MALE = 'MA' FEMALE = 'FE' SHINY = 'SHI' NORMAL = 'NOR' EGG = 'EGG' CHILD = 'CHI' ADOLESCENT = 'ADO' ADULT = 'ADU' ELDER = 'ELD' BIGBONED = 'BIGB' BUTTERFACE = 'BUTT' CHARMED = 'CHAR' CHATTY = 'CHAT' CONSTIPATED = 'CONS' CURVY = 'CURV' EVIL = 'EVIL' EXALTED = 'EXAL' FORTUNATE = 'FORT' FREAKOFNATURE = 'FREA' FROSTBREATH = … -
my css, js and imgs files are not comming in static folder
After running the following command for the Django project: python manage.py collectstatic Some other CSS files are generated, but the following CSS files "that exist in my template folder" are not coming into a static generated folder. When I manually copy-paste these files after the command then it works on local to load, but on production upon deployment to Heroku, it again runs collecstatic command which overwrites those files and then it doesn't load. I also have disabled collect static upon deploying the project to Heroku to prevent overwriting then again it does not load CSS files from the static folder. Please, does anyone, know how I could deal with it? thanks in advance -
Django tests fail due to null ids in content_type table depending on app naming
I added a new app to an established Django project with a PostgreSQL DB. The app name begins with an "a". The app models have foreign keys to models in other apps. The migrations run with no issue and the application starts and runs fine. However, running the tests gives an error like the below as soon as the test database creation starts. Each run creates an error for a different model. From this we can see that content_type table is being populated with null values for the ids. django.db.utils.IntegrityError: null value in column "name" of relation "django_content_type" violates not-null constraint DETAIL: Failing row contains (1, null, threadedcomments, threadedcomment). I have dependencies defined in the migrations file to ensure DB tables are created in the correct order. I have also moved the new app to the end of the list in the INSTALLED_APPS setting. Everything runs as it is supposed to if I do either of the following. Rename the app to start with a different letter. Removing the foreign keys. It looks like the tables are being created alphabetically, despite the migration dependencies. Is there a way to force the order of the table creation? Or is there something … -
rest_marshmallow: Nested Schema isn't loading
I have trouble getting the nested Schema loaded using marshmallow serializer. models.py from django.db import models class User(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.CharField(max_length=200, unique=True) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) class Upload(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) state = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) class Location(models.Model): upload = models.ForeignKey(Upload, on_delete=models.CASCADE) lat = models.FloatField() long = models.FloatField() serializers.py from rest_marshmallow import Schema, fields class LocationSchema(Schema): lat = fields.String() long = fields.String() class UploadsSchema(Schema): id = fields.Integer() state = fields.String() location = fields.Nested(LocationSchema) user_id = fields.Integer() created = fields.DateTime() class UserSchema(Schema): id = fields.Integer() first_name = fields.String() last_name = fields.String() email = fields.Email() created = fields.DateTime() last_updated = fields.DateTime() views.py class UploadsView(ListView): def get(self, request, user_id): upload = Upload.objects.filter(user_id=user_id) serializer = UploadsSchema(upload, many=True) return JsonResponse(serializer.data, safe=False) def post(self, request, user_id): data = json.loads(request.body) user = User.objects.get(id=user_id) upload = Upload(state=data['state'], user=user) upload.save() recent_upload = Upload.objects.filter(user_id=user_id).latest('created') location = Location(lat=data['lat'], long=data['long'], upload=recent_upload) location.save() message = { "data": "Success" } return JsonResponse(message, safe=False) GET on UploadsView returns all the fields except the Nested field. Here's a sample response: { "user_id": 2, "id": 5, "created": "2022-08-05T17:44:30.829087+00:00", "state": "happy" } I tried location = fields.Nested(LocationSchema(many=True)), but that doesn't seem to work either. What am I doing … -
Error during run the program runtime error
These are apps installed in my django project , the apps with vip_number.* are inside the innerproject folder... but i got the issue here that my apps are not installed in seetings.py where as they are already there INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'jet', 'jet.dashboard', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'vip_number.users', 'vip_admin', 'vip_number.base', 'vip_number.categories', 'vip_number.category_tag', 'vip_number.category_numbers', 'vip_number.number', 'vip_number.paytm', 'vip_number.subscribers', 'vip_number.homeimages', 'vip_number.testimonial', 'vip_number.faq', 'tagconstants', 'sekizai', 'vip_number.wawebplus', 'contact', ] error :*********************************************************************************** (djangoenv) PS E:\download\VIP number\vip_number> python manage.py runserver Exception in thread django-main-thread: Traceback (most recent call last): File "E:\download\VIP number\djangoenv\lib\site-packages\django\apps\config.py", line 244, in create app_module = import_module(app_name) File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'base' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "E:\download\VIP number\djangoenv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "E:\download\VIP number\djangoenv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "E:\download\VIP number\djangoenv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "E:\download\VIP number\djangoenv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "E:\download\VIP number\djangoenv\lib\site-packages\django\utils\autoreload.py", … -
How can I set a logic like, "If a user order any product then the user will be able to give feedback just on that product"?
My motive is to set a logic like, a user only will be able to give a product review on that product he/she bought. I tried this below way but didn't work. Please give a relevant solution models.py class Products(models.Model): user = models.ForeignKey(User, related_name="merchandise_product_related_name", on_delete=models.CASCADE, blank=True, null=True) product_title = models.CharField(blank=True, null=True, max_length = 250) def __str__(self): return str(self.pk) + "." + str(self.product_title) class ProductOrder(models.Model): User = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='UserOrderRelatedName',on_delete=models.CASCADE) CustomerName = models.CharField(max_length=250, blank=True, null=True) Product = models.ForeignKey(Products, related_name='ProductOrderRelatedName',on_delete=models.CASCADE) ProductTitle = models.CharField(max_length=250, blank=True, null=True) def __str__(self): return f'{self.pk}.{self.User}({self.Product})' views.py: def quick_view(request, quick_view_id): quick_view = get_object_or_404(Products, pk=quick_view_id) context = { "quick_view":quick_view, } return render(request, 'quickVIEW_item.html', context) urls.py: path('quick_view/<int:quick_view_id>/', views.quick_view, name="quick_view"), template: {% if quick_view in request.user.UserOrderRelatedName.all %} <form action="{% url 'feedBack' quick_view_id=quick_view.id %}" method="POST" class="needs-validation mt-3" style="font-size: 13px;" novalidate="" autocomplete="off" enctype="multipart/form-data"> {% csrf_token %} <textarea id="email" placeholder="Share your experiencs..." rows="10" style="font-size: 13px;" type="email" class="form-control" name="feedBACK" value="" required></textarea> <button type="submit" class="btn btn-outline-dark ms-auto" style="font-size: 13px;"> Submit </button> </form> {% endif %} -
table post_post has no column named publishing_date
im just a beginner in web coding and i got this error while i was adding my first app to the my first website i couldn't find a solution to this i thought it was something related to language of my website but it didn't worked and here is my codes that i just wrote like i said i just started to coding so i dont know anything to solve this issue enter image description hereenter image description here -
django show me "django.db.models.query_utils.DeferredAttribute object at"
Im trie to get a values from an object of my DB on a form in html to edit him but when i call the current "value" from the attribute i get this: Form HTML <form enctype="multipart/form-data" method="post"> {% csrf_token %} {% for campo in formulario %} <div class="mb-3"> <label for="" class="form-label">{{ campo.label }}:</label> {% if campo.field.widget.input_type == 'file' and campo.value %} <br/> <img src="{{MEDIA_URL}}/imagenes/{{campo.value}}" width="100"srcset=""> {% endif %} <input type="{{ campo.field.widget.input_type}}" class="form-control" name="{{ campo.name }}" id="" aria-describedby="helpId" placeholder="{{campo.label}}" value="{{campo.value | default:''}}" /> </div> <div class="col-12 help-text"> {{campo.errors}}</div> {% endfor %} <input name="" id="" class="btn btn-success" type="submit" value="Enviar informacion"> </form> Views Models -
Django Rest Framework permissions class doesn't work properly
I'm trying to implement view with rest-framework, here it is: class IsOwnerOnlyPermissions(BasePermission): def has_object_permission(self, request, view, obj): print(obj.user_profile.user, request.user, obj.user_profile.user == request.user) print(request.user.groups, request.user.get_group_permissions()) return obj.user_profile.user == request.user class DjangoModelPermissionsWithRead(DjangoModelPermissions): perms_map = { 'GET': ['%(app_label)s.view_%(model_name)s'], 'OPTIONS': [], 'HEAD': [], 'POST': ['%(app_label)s.add_%(model_name)s'], 'PUT': ['%(app_label)s.change_%(model_name)s'], 'PATCH': ['%(app_label)s.change_%(model_name)s'], 'DELETE': ['%(app_label)s.delete_%(model_name)s'], } class DocumentsDetails(generics.RetrieveAPIView): queryset = Documents.objects.all() serializer_class = DocumentsSerializer # Can access only owner OR administrator/moderator permission_classes = [IsOwnerOnlyPermissions | DjangoModelPermissionsWithRead] But it doesn't work properly. I'm accessing it via Postman with user which doesn't have any permissions or groups (it's printing auth.Group.None set()) and it doesn't block access for me. I know, that I can check user permissions in my IsOwnerOnlyPermissions, but I want to use DjangoModelPermissions class for this. Are there any possibility to do this? -
column does not exist at.... programmeable error
i have carried out all my migrations but still receiving this error. To my understanding the error means that the product table does not have the entities like name, price etc yet they are there. I need some help understanding this error more. from audioop import add from termios import TIOCGWINSZ from django.db.models.deletion import CASCADE from django.urls import reverse from django.conf import settings from django.db import models from django.conf import settings CATEGORY_CHOICES = ( ('F', 'Fashion'), ('El', 'Electronics'), ('HB', 'Health & Beauty'), ('G', 'Gardening'), ('SP', 'Sports'), ('HO', 'Home & Office'), ) LABEL_CHOICES = ( ('P', 'Primary'), ('S', 'Secondary'), ('D', 'Danger'), ) class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7, decimal_places=2, null=True) seller = models.CharField(max_length=200, blank=True, null=True) discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2, null=True) label = models.CharField(choices=LABEL_CHOICES, max_length=2, null=True) image1 = models.ImageField(null=True, blank=True) image2 = models.ImageField(null=True, blank=True) image3 = models.ImageField(null=True, blank=True) image4 = models.ImageField(null=True, blank=True) slug = models.SlugField(null=True, blank=True) characteristics = models.TextField(max_length=3000, null=True) description = models.TextField(max_length=3000, null=True) specifications = models.TextField(max_length=3000, null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("homeapp:product", kwargs={'slug': self.slug}) def get_add_to_cart_url(self): return reverse("homeapp:add-to-cart", kwargs={'slug': self.slug}) def get_remove_from_cart_url(self): return reverse("homeapp:remove-from-cart", kwargs={'slug': self.slug}) @property def image1URL(self): try: url = self.image1.url except: url = '' return url @property def image2URL(self): … -
Save large CSV data into Django database fast way
I am trying to upload extensive CSV data like 100k+ into the Django database table, I have created the model below and then made a save function to insert the data into the table. It takes a long time so I have written celery code to run this in the background so it doesn't timeout, But the saving data into the table is slower. Is there any way to make the saving faster? class Film(models.Model): title = models.CharField(max_length=200) year = models.PositiveIntegerField() genre = models.ForeignKey(Genre, on_delete=models.CASCADE) def save_csv_to_db(): with open('films/films.csv') as file: reader = csv.reader(file) next(reader) for row in reader: print(row) genre, _ = Genre.objects.get_or_create(name=row[-1]) film = Film(title=row[0], year=row[2], genre=genre) film.save() -
Problem trying validate django form field while typing
I'm trying validate a field while typing based on another question ( How to validate django form field while it is typing? ). the js don't cal validation view and i get this error in browser: Uncaught ReferenceError: $ is not defined for line $('#id_num').on('input', function () { form {{ form.num }} <p id="validate_number" class="help is-danger is-hidden ">nome já utilizado</p> js <script> $('#id_num').on('input', function () { var id_number = $(this).val(); $.ajax({ url: '/validatenum/', data: { 'num': id_number }, dataType: 'json', success: function (data) { if (data.is_taken) { $("#validate_number").show(); document.getElementById('id_num').style.borderColor = "red"; document.getElementById("submit_change").disabled = true; } else { $("#validate_number").hide(); document.getElementById('id_num').style.borderColor = "#e7e7e7"; document.getElementById("submit_change").disabled = false; } } }); }); </script> view def validate_inventory_number(request): number = request.GET.get('num', None) data = { 'is_taken': InventoryNumber.objects.filter(num=number).exists() } return JsonResponse(data) -
Django pagination: EmptyPage: That page contains no results
When using Django CBV ListView with pagination, if I provide a page that is out of range, I get an error: I would like to have a different behaviour: to fallback to the last existing page if the provided page is out of range. I dug into Django source code paginator.py file and was surprised to find some code that does exactly this: def get_page(self, number): """ Return a valid page, even if the page argument isn't a number or isn't in range. """ try: number = self.validate_number(number) except PageNotAnInteger: number = 1 except EmptyPage: number = self.num_pages return self.page(number) However, it seems this code is never called by default using Pagination. What is the right way to deal with this? Should I make my own paginator by subclassing the Paginator class? Thanks. -
No Module named WhiteNoise
2022-08-05T17:47:45.758949+00:00 app[web.1]: ModuleNotFoundError: No module named 'whitenoise' 2022-08-05T17:47:45.759055+00:00 app[web.1]: [2022-08-05 17:47:45 +0000] [10] [INFO] Worker exiting (pid: 10) 2022-08-05T17:47:45.817101+00:00 app[web.1]: [2022-08-05 17:47:45 +0000] [11] [ERROR] Exception in worker process ""hello, I am getting this error while uploading my Django to the heroku""" -
Field 'id' expected a number but got ' '. But I dont even have a field named 'id'
we are making a web app using Django, postgresql, and reactjs. I am creating two models and connecting them using one to one relationship in django. The view file is literally empty. This is models.py file I changed the primary key fields for each table to avoid the error but it isnot solving anything.I am new to Django. Please help. from django.db import models class userInfo(models.Model): Username=models.CharField(max_length=100,primary_key=True) Password=models.CharField(max_length=100) def __str__(self): return self.Username class rentDetails(models.Model): user=models.OneToOneField( userInfo, on_delete=models.CASCADE, primary_key=True ) floor_no=models.CharField(max_length=20,default=True) distance=models.IntegerField(default=True) location=models.CharField(max_length=200,default=True) area=models.IntegerField(default=True) no_of_rooms=models.IntegerField(default=True) price=models.IntegerField(default=True) property_choices=[ ('hostel','Hostel'), ('house','House') , ('room','Room'), ('flat','flat') ] property_type=models.CharField( max_length=10, choices=property_choices, ) images=models.ImageField(upload_to='uploads/',null=True)