Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Neovim for Django: metaclasses are not recognized
Image of Error Message in Neovim I have been trying to configure my neovim for django development and everything seems fine except for this issue I am having with fields in metaclasses. the image provided gives a snapshot and the code is as follows: class UserSerializer(serializers.ModelSerializer): snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all()) the linting error indicates that it cannot access member objects for the Snippet class. I am using coc-pyright with default settings. I tried playing around with the settings by enabling pylint and installing pylint-django in my project as a dev dependency but that was unable to resolve the issue. How would I fix this issue? Does anyone have a recommended setup for Django development in nvim? -
django-ckeditor change upload path prefix
I want to change the prefix of upload path in django-ckeditor. By default it generates subdirectories by using username and date so something like: /media/uploads/username/year/month/day/uploaded_file The documentation says: Set the CKEDITOR_RESTRICT_BY_USER setting to True in the project’s settings.py file (default False). This restricts access to uploaded images to the uploading user (e.g. each user only sees and uploads their own images). Upload paths are prefixed by the string returned by get_username. If CKEDITOR_RESTRICT_BY_USER is set to a string, the named property is used instead. After few tries, still can't figure out how to configure this to handle prefix of uploaded files. Thanks for any help. -
How to manage a Django Rest Framework codebase when API versions change?
There's plenty of topics about api versioning. But many don't discuss how versioning affects the codebase. How do you go about managing the codebase when the version changes? Examples would be appreciated. Example: codebase for version 1 Default versioning: NamespaceVersioning Model: class Book(models.Model): name=models.CharFiedl(max_length=20) pages=models.IntegerField() view: class BookView(views.ViewSet): def List(self, request): books = Books.objects.all() return Response(BookSerializer(books, many=True).data) serializer: class BookSerializer(serializers.ModelSerializer): class Meta: fields = ['name', 'pages'] What would the code and folder structure for version 2 look like when breaking changes are introduced? -
Python SQLite3 - Is there a way to search for a table based on user input without injection risk?
I have a website where a user can select from multiple tables to browse data, but I am having trouble accomplishing this in a way that doesn't expose my website to injection since you cannot do parameterized searches for tables, columns ect. What I want to do is this: cursor.execute("SELECT * FROM ?", (selected_table,)) which returns an error and forces me to do this to make it work: cursor.execute("SELECT * FROM {0} ".format(selected_table)) which exposes my server to injection. Is there any way around this? -
AJAX Call Prompting Up the "Print Page" Option
I have a dropdown that on change, calls an AJAX function, which just stores the dropdown value into the session (this is not the issue, I've commented it out and same issue occurs), and when this AJAX function comes back successfully, it seems to prompt up the Print Page feature. I feel like this help with some answers: the url is "/app/newgroup/230/2/ajax_settings_dropdown?dropdownValue=224". I mention this because based on that second number (in this URL, it is 2), it'll prompt the print page that amount of times every time something is selected. Dropdown and AJAX fnc: <div class="form-group"> <b><label>Choose settings from existing project:</label></b> <select class="form-control" id="ProjectSelect"> <option selected="selected" disabled value=0> Select a setting </option> {% for sID in settingsInfo %} <option value="{{ sID.1 }}"> {{sID.0}} </option> {% endfor %} <option value=0> None </option> </select> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script> $('#ProjectSelect').on('change', function () { var units = { dropdownValue: $(this).val() }; $.ajax({ url: 'ajax_settings_dropdown', async: true, data: units, success: function () { print("SUCCESS"); }, error: function () { print("Oops"); } }); }); </script> views.py: def update_settings_dropdown(request, project_id, groups_num): dropdownValue = request.GET.get('dropdownValue') if dropdownValue != 0: currG_sID = request.session.get('createdGroups_sID') currG_sID.append(dropdownValue) request.session['createdGroups_sID'] = currG_sID return render(request, 'EmptyPage.html') urls.py path('app/newgroup/<str:project_id>/<str:groups_num>/ajax_settings_dropdown', views.update_settings_dropdown) -
django custom Func for specific SQL function
I'm currently performing a raw query in my database because i use the MySQL function instr. I would like to translate is into a django Func class.I've spend several days reading the docs, Django custom for complex Func (sql function) and Annotate SQL Function to Django ORM Queryset `FUNC` / `AGGREGATE` but i still fail to write succesfully my custom Func. This is my database from django.db import models class Car(models.Model): brand = models.CharField("brand name", max_length=50) #then add the __str__ function Then I populate my database for this test Car.objects.create(brand="mercedes") Car.objects.create(brand="bmw") Car.objects.create(brand="audi") I want to check if something in my table is in my user input. This is how i perform my SQL query currently query = Car.objects.raw("SELECT * FROM myAppName_car WHERE instr(%s, brand)>0", ["my audi A3"]) # this return an sql query with one element in this example I'm trying to tranform it in something that would look like this from django.db.models import Func class Instr(Func): function = 'INSTR' query = Car.objects.filter(brand=Instr('brand')) -
How can i check if my query was done successfully
I'm working on a small project using Django/Rest with Tenants-Package and Celery so i would like to know if my tenants has been created successfully or no how can i check ( any way to return true or false ) by cheking if is saved or no ? this is my code : @shared_task @transaction.atomic def createUserTenant(userid): with schema_context('public'): userInQuestion = CustomUser.objects.get(id=userid) # create your first real tenant tenant = Client(schema_name=str(userInQuestion.username), name=userInQuestion.first_name + '_' + userInQuestion.last_name, paid_until='2014-12-05', on_trial=True) tenant.save() # migrate_schemas automatically called, your tenant is ready to be used! # Add one or more domains for the tenant domain = Domain() domain.domain = str(userInQuestion.username) + settings.BASE_URL domain.tenant = tenant domain.is_primary = False domain.save() -
Drawing graphs based on data in the database
I need to draw graphs based on data from models. How can this be done? Model adress = models.ForeignKey(Parking, on_delete=models.SET_NULL, null=True) carnumber = models.CharField(max_length=150) amountoftime = models.IntegerField() price = models.FloatField() telephone = models.CharField(max_length=20) email = models.EmailField(null=True,blank=True ) datetimepaidparking = models.DateTimeField(auto_now_add=True) expirationdate = models.DateField(null=True) expirationtime = models.TimeField(null=True) enddateandtime = models.DateTimeField(null=True,blank=True) I need to create a schedule for a certain period of time(month, day, week) -
How do I integrate a filter into my Django website?
I'm creating a Django website where users (who are learning Chinese) can upload Chinese vocabulary lists and the site will return a list of just the unique characters (no duplicates) that the user can download. So far, it's working and doing everything I described above. But the part that I'm stuck on is that I want to add a filter functionality. I want to add the option to exclude some of the more common Chinese characters from the list that the user downloads (what I'm thinking of as a filter feature). So, for example, I want to add radio buttons where, before the user presses upload, they first say whether they want to filter out the 100 most common characters, 500, none, etc. Then, it should take that into account when it's writing to the file that it presents for the user to download. I would provide some code, but I'm just not sure where to start. So far, I've created most of the site in views and my template. Can I do all of this in views? Should I put the files of the characters I want to filter in my static files? Should I do it through a … -
"placeholder-shown" selector not working with django forms
I have input fields that lower label when something has been typed in it. paste bin css <div class="form__group"> <input type="text" class="form__input" id="name" placeholder="Full name" required="" autocomplete='off' /> <label for="name" class="form__label">Full Name</label> </div> But, when I use django forms, they don't work at all <div class="form__group col"> {{createSet.title}} <label for="id_title" class="form__label">Title</label> </div> -
django - Foreign key not getting created from model
I have created below model with foreign key but migration file does not have any foreign key and hence in sql server database also foreign key relationship is not getting created models.py class RetailerMaster(models.Model): id = models.PositiveIntegerField(unique=True) name = models.CharField(max_length=1000) address = models.CharField(max_length=4000) city = models.CharField(max_length=100) state = models.CharField(max_length=100) pincode = models.CharField(max_length=100) contact_name = models.CharField(max_length=500) email = models.EmailField() phone = models.CharField(max_length=15) erp = models.CharField(max_length=1000) remark = models.CharField(max_length=4000) def __str__(self): return self.id class FileUpload(models.Model): retailer_id = models.ForeignKey(RetailerMaster, on_delete=models.CASCADE), file = models.FileField(upload_to='files') file_upload_datetime = models.DateTimeField() file_name = models.CharField(max_length=1000) migrations file migrations.CreateModel( name='FileUpload', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('file', models.FileField(upload_to='files')), ('file_upload_datetime', models.DateTimeField()), ('file_name', models.CharField(max_length=1000)), ], ) What am i doing wrong that foreign key is not getting created. Basically, what i am implementing is, for one RetailerMaster record multiple files can be uploaded. -
Google Calendar OAuth 2.0 Error 403: access_denied
I have been trying to gain authorization from the Google Calendar API on my site so that I can access user calendar data. When I issue an HttpResponseRedirect from the desired view on my site via Django (to send the user to Google so they can provide the necessary permissions), the redirect works as expected. The issue is that on Google it's returning "error 403: access denied", along with a message stating that the developer must authorize my account before I can use the API (I'm trying to use a different Google account to log in for the purpose of testing). I've poked around the Google API site, but can't find where this authorization occurs. Any idea of where I might find this? Full Specific Error Message. -
DRF Protect user registration view
I have a following user view: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer permission_classes = [NotSafeMethodAndAllowAny | permissions.IsAuthenticated] def get_queryset(self): if self.request.user.is_superuser: return User.objects.all() else: return User.objects.filter(id=self.request.user.id) @action(detail=False, methods=["get"]) def current(self, request, *args, **kwargs): return Response(self.get_serializer(request.user).data) As this is a ModelViewSet, it allows API users to create, list, update, delete the users. Don't mind the NotSafeMethodAndAllowAny permission. Now I want to somehow protect my API from the users using it like in a script. For example, when I submit the user registration form on my frontend (a separate React app), it should be accepted, but if someone posts to my api/user/ with random registration data like from Postman/curl/etc., I want it to be discarded. Is there a way for DRF to distinguish between those two types of requests? And possibly via some setting, so I can test it via Postman when in development, but when it runs in production, it would not accept automated requests. I want to prevent a situation where someone would create like a bazillion users in a matter of minutes. BTW: I use JWT for authentication, but for obvious reasons the registration/login endpoints do not require authentication. -
Suddenly We're not able to add more images in specific page in Wagtail with 400 Bad Request Error
This is the Gallery Page models, we've added 142 image so far, and we're able to add more images in other pages, but on this one, even if I delete an image and try to add another one I got an 400 Bad Request on publishing and Error while sending preview data. on previewing class Gallery(Page): content_panels = Page.content_panels + [ InlinePanel('media', label=_('Gallery Media')) ] class GalleryMedia(ClusterableModel, Orderable): category = ParentalManyToManyField("gallery.GalleryCategory", blank=True) gallery = ParentalKey( "gallery.Gallery", on_delete=models.CASCADE, related_name="media", null=True ) image = models.ForeignKey( "wagtailimages.Image", on_delete=models.CASCADE, related_name="+", null=True, blank=True, help_text="The recommended sizes and dimensions for the images are: 350*200 / Aspect Ratio 7 : 4 - 350*700 / Aspect Ratio 1 : 2 - 350*500 / Aspect Ratio 7 : 10" ) video_url = models.URLField(blank=True) video = models.ForeignKey( "wagtailvideos.Video", related_name="+", null=True, blank=True, on_delete=models.SET_NULL, ) show_large = models.BooleanField(default=False) show_on_homepage = models.BooleanField(default=False, verbose_name="Show on HomePage") panels = [ ImageChooserPanel("image"), FieldPanel("video_url"), VideoChooserPanel("video"), FieldPanel("show_large"), FieldPanel("show_on_homepage"), MultiFieldPanel([FieldPanel("category", widget=CheckboxSelectMultiple),]), ] class GalleryCategory(models.Model): name = models.CharField(max_length=50) panels = [ FieldPanel("name"), ] -
ModuleNotFoundError: No module named 'users.urls'
from django.contrib import admin from django.conf.urls import include, url urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^users/', include(('users.urls', 'users'), namespace = 'users')), url(r'', include(('learning_logs.urls', 'learning_logs'), namespace = 'learning_logs')), ] When I run the server It gives the above error -
Cloudant local cache not syncing with local couch cache. Using python-cloudant
I am new to couch DB and cloudant. A django application is converting a pdf into image using a celery task and storing both in couch DB. But the local cloudant cache is not updating, since couch DB updation is causing by the celery task. When checking the local cache, it's storing a previous doc object with old revision number. Remote couch DB is updating fine and not syncing with local. Why couch updations from celery is not affecting local cache Is anything I am doing wrong -
How to disable default Django-Rest Error pages
How I can disable the default Django-Rest error pages and create my customer page for any exception. -
In production Django {{object.image.url}} not working in production. How to show image/MEDIA_ROOT/ in production?
When I set DEBUG=False in app/settings.py {{object.img.url}} not working. How to fix this? when I inspect it's img.url getting /images/image_name.jpg like this. In DEBUG=True http://127.0.0.1:8000/images/image_name.jpg it shows image. But when I set DEBUG=False this http://127.0.0.1:8000/images/image_name.jpg this didn't show anything. my media root MEDIA_URL = '/images/' MEDIA_ROOT = (BASE_DIR / 'static/images') in my URL I added urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) How to show image/MEDIA_ROOT/ in production. -
Why does nose ignore certain files on coverage report?
I am running tests on a project I've been assigned to. Everything is triggered by calling tox. Default tests run with nose, which adds a coverage report, this is the command that tox calls: django-admin test -s and settings file has this configuration for nose: NOSE_ARGS = [ '--with-coverage', '--cover-erase', '--cover-package=app_name', '--cover-inclusive' ] This is the report that's shown while running nose with tox: Name Stmts Miss Cover --------------------------------------------------------------------------- app_name/__init__.py 0 0 100% app_name/apps.py 3 0 100% app_name/apps_settings.py 12 2 83% app_name/base.py 118 27 77% app_name/choices.py 18 0 100% app_name/constants.py 6 0 100% app_name/exceptions.py 10 0 100% app_name/helpers/__init__.py 0 0 100% app_name/helpers/util.py 20 10 50% app_name/management/__init__.py 0 0 100% app_name/migrations/0001_initial.py 9 0 100% app_name/migrations/__init__.py 0 0 100% app_name/mixins.py 6 0 100% app_name/models.py 64 4 94% app_name/permissions.py 7 3 57% app_name/serializers/__init__.py 0 0 100% app_name/serializers/address_serializer.py 7 0 100% app_name/serializers/base_response_serializer.py 7 0 100% app_name/serializers/body_request_user_serializer.py 14 0 100% app_name/serializers/contact_serializer.py 4 0 100% app_name/serializers/file_serializer.py 11 2 82% app_name/serializers/iban_serializer.py 3 0 100% app_name/serializers/identification_serializer.py 11 2 82% app_name/serializers/payment_account_serializer.py 3 0 100% app_name/serializers/transfer_serializer.py 20 10 50% app_name/services/__init__.py 0 0 100% app_name/services/authentication_service.py 7 0 100% app_name/services/document_service.py 23 9 61% app_name/services/user_service.py 37 21 43% app_name/services/webhook_service.py 26 7 73% app_name/storage_backends.py 10 0 100% app_name/views/__init__.py 0 0 100% app_name/views/webhook_view.py 25 8 … -
Django Channels error: You have not set ASGI_APPLICATION, which is needed to run the server
I am creating a game with Django and Django Channels, but when I run the server, I get the following error. CommandError: You have not set ASGI_APPLICATION, which is needed to run the server. Here is the channel_layers section of the settings.py file CHANNEL_LAYERS = { "default": { "BACKEND": "asgiref.inmemory.ChannelLayer", "ROUTING": "obstruction.routing.channel_routing", }, } -
How do I fetch and send Data from multiple models in Django?
I'm Trying to send data about all the available retailers and their prices for a particular product. How should I approach creating the view for it? Here are my models: class Product(models.Model): name = models.CharField(max_length=30,null=True,blank=True) brand = models.CharField(max_length=20,null=True,blank=True) image = models.ImageField(null=True,blank=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return self.name class Retailer(models.Model): name = models.CharField(max_length=20,null=True,blank=True) image = models.ImageField(null=True,blank=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return self.name class RetailerProduct(models.Model): url = models.CharField(max_length=300,null=True,blank=True) price = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True) difference = models.DecimalField(default=0.00,max_digits=8,decimal_places=2,null=True,blank=True) retailer = models.ForeignKey(Retailer, on_delete=models.CASCADE) available = models.BooleanField(default=False) _id = models.AutoField(primary_key=True, editable=False) product = models.ForeignKey(Product, on_delete=models.CASCADE) def __str__(self): return self.retailer.name + " - " + self.product.name Here is the JSON data I would like to send. { '_id': '2', 'name': 'ProductName', 'image': '/images/ProductName.jpg', 'description':'', 'brand': 'brandname', 'category': 'categoryname', 'price': 599.99, 'Instock': False, 'ranking': 10, 'numSources': 4, 'sources':[{'Retailer':'Amazon', 'Price':'799.99'}, {'Retailer':'Onbuy', 'Price':'599.99'}, {'Retailer':'Ebay', 'Price':'599.99'}, {'Retailer':'NewEgg', 'Price':'499.99'}], }, Here Is my current view for getting a specific product: class getProduct(APIView): def get(self, request,pk): product = Product.objects.get(_id=pk) serializer = ProductSerializer(product,many=False) return Response(serializer.data) The serializer just has field = '__all__' Any help would be much appreciated. -
Django reduce list of nested Q objects into a filter
I've dynamically created a list of Q objects such that the final result is either ( AND: {'additional_si_prop_description__exact': 'Field Not Present'}, ( OR: {'additional_si_prop_name__icontains': 'name of ticket'}, {'additional_si_prop_comment_count__gt': 100.0} ) ) I created this via recursively going through a list and applying reduce at each level of the list with: def _reduce(q): bunch of code in here to loop through things... return reduce(or_, filter_list) but when I attempt to apply that value to a filter I get the error Cannot parse keyword query as dict is there a way to turn that value into an acceptable filter? -
Django Not working properly in visual studio
This is my first post so please spare me with any mistake. I have been working with Python for 2 years as a student and now I wanted to use it to create web applications. But I found an error on my visual studio code. I used "python manage.py runserver hello" to run Django but it did worked. It said, "Directory Not found". I have installed the Python and Django successfully and I can see the manage.py file in my folder but I am unable to run it. Please tell me how can I run it? I am attaching that thing- PS C:\Users\Admin\Desktop\Atharwa\Atharwa coding\Web application programming> python manage.py --version C:\Users\Admin\AppData\Local\Programs\Python\Python38\python.exe: can't open file 'manage.py': [Errno 2] No such file or directory But, I do have a file named manage. So, please tell me how can I run it? -
Django Admin Inlines error "MultipleObjectsReturned at"
I have a many-to-many relationship connecting 3 models. like this: ucn-\ \ |-ucn2tipoveg Many to many! / Tipoveg-/ It works but when i try to edit an entry on my django admin it returns this error: MultipleObjectsReturned at /admin/accounts/ucs/211/change/ get() returned more than one Ucn2Tipoveg -- it returned 3! models.py: class Tipoveg(models.Model): tipoveg_id = models.AutoField(primary_key=True) nometipoveg = models.CharField(db_column='nomeTipoVeg',blank=True, null=True) class Meta: managed = False class Ucs(models.Model): ucn_id = models.AutoField(primary_key=True,db_column='ucn_id') nome = models.CharField(verbose_name="nome",max_length=255, blank=True, tipo = models.ManyToManyField(Tipoveg, through='Ucn2Tipoveg') class Meta: managed = False def get_default_ucn(): return Ucn2Tipoveg.objects.latest('ucn2tipovegid').ucn2tipovegid+1 class Ucn2Tipoveg(models.Model): ucn= models.ForeignKey(Ucs, models.DO_NOTHING,db_column='ucn_id') tipoveg = models.ForeignKey(Tipoveg, models.DO_NOTHING) ucn2tipovegid = models.AutoField(primary_key=True,default=get_default_ucn) class Meta: managed = False unique_together = (('ucn_id', 'tipoveg'),) -
Remove the database exception error on a page reload
I am on Django Framework and implemented an interface where a user can do Insert and Update operations on a MySQL table. My table does not allow duplicates, so I display an Exception error to the user to let them know their request failed. However, when I reload the page the error message still get's displayed when it shouldn't. The message only disappears when I submit a successful request that has no duplicates. It seems like the error message keeps getting displayed because on page reload it is returning a POST request and it re-enters the duplicate key which spits out the Exception message. How can I stop this request from submitting twice, or is there a better approach to accomplish this? views.py def generate_student_info(request): # Retrieve inputted value current_student_name = request.POST.get('student_name') current_student_id = request.POST.get('student_id') # Read the table from the database connection = db.open_connection(read_only=False) sql_str = f"""SELECT * FROM {students_table};""" df = db.read(sql_statement=sql_str, connection=connection) # creating a formset insert_formset = formset_factory(StudentInfoForm, extra=0) formset = insert_formset(request.POST or None, initial=[{'student_id': df['student_id'][i], 'student_name': df['student_name'][i]} for i in range(len(df))]) context = {'formset': formset, 'db_error_message': '', 'display_error_message': False} if request.method == 'POST': # Insert MySQL query if 'student_name' in request.POST: try: insert_query = f"""INSERT …