Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django - Multiple File upload data not inserted in model database
I have implemented a feature to upload multiple files for each RetailerMaster(as foreign key). Once I migrate this model to microsoft sql server, FileUpload model is created without primary key which django should be creating automatically. Also if i upload multiple file, then only one record is created in database and it keeps on updating for each file. 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 = 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) views.py retailer = RetailerMaster.objects.get(retailer_id=retailer_id) register_complete = retailer files = request.FILES.getlist('file') file_upload_datetime = file_upload_form.cleaned_data['file_upload_datetime'] for f in files: print(f.name) file_instance = FileUpload(register_complete.id,f,file_upload_datetime,f.name) file_instance.save() eg: If two files are uploaded 001.xlsx and 002.xlsx then below happens in database. As actual result, one record is inserted rather than two and same is updated with last file uploaded from multiple files. Can anyone help why record is not inserted but just updated. -
Login with django rest auth and mongodb
im very new to python and django. Currently experimenting on django-rest-auth and mongodb. So, im trying to set up a login and registration page. The registration works , ie save users in the DB, although i have this error TypeError at /rest-auth/registration/ Field 'id' expected a number but got ObjectId('6092cac59ab89b918140dcab'). From what i gathered, i should create a custom user model (or document?) and set a primary key so django does not add one? Back to the login issue, which is ValueError at /rest-auth/login/ save() prohibited to prevent data loss due to unsaved related object 'user'. The POST method does access the right collection in the DB , because i cannot login with invalid credentials. This error appear once i have successfully (?) logged in. After searching for a few hours, im nowhere. I found nothing, i dont know why the save() method would be called after a login. Ill be thankful for any pointers in the right direction. -
How to correctly configure Django to send emails with Gmail and what are the correct settings for the Gmail account?
I would appreciate some help with setting up Gmail with a Django application. I am trying to send send an email using gmail through Django to reset user passwords. My settings.py SMTP configuration is: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASWORD = 'mypassword' For the password I tried using both, the actual account password and the generated 16 digit password for apps which don't support 2-step authentication. I enabled the IMAP access and access for less secure apps in my gmail settings. I am still getting this error when trying to reset the password on my Django app: SMTPSenderRefused at /reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError s21sm6387949wmc.10 - gsmtp', 'webmaster@localhost') Any ideas what am I doing wrong? I am not sure if this is an issue with my configuration in Django or Gmail settings. Thanks in advance. -
Upload large video file in Django asynchronously
For one of the projects I need to upload a large video file(>1GB) to Django server. from django.db import models class Video(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True, verbose_name="") Issue is, it is taking a long time. In production this will cause error as it will be a bad user experience and secondly it will throw error with nginx server more than 30 sec. Is there any way to upload the file to the server asynchronously using the same model...?? -
Error AttributeError: 'str' object has no attribute 'year' when querying a model
I get startdate and enddate, but they are passed as a string. How do I convert them to a date? startdate = request.POST["startdate"] enddate = request.POST["enddate"] queryset = paidparking.objects.all() qsstats = QuerySetStats(queryset, date_field='expirationdate') values = qsstats.time_series(startdate, enddate, interval='days') return render(request, 'index/template.html', {'values': values}) Error in: values = qsstats.time_series(startdate, enddate, interval='days') -
Creating A Checklist Template And Generating An Individual Checklist For Each User In Django
I am working on a project that incorporates a checklist for each new user. I had set it up so that the checklist is a model and used a foreignKey to associate the checklist with the correct user. I realize, however, that this would force me to re-create the checklist from scratch for each user. I would like, instead, to create a template with all of the ToDo items on it and then as users join the service a new instance of the checklist is created for them. I thought about doing a ManyToManyField for each checklist. This would probably mean, however, that if one user checks off one of their ToDos everyone's ToDo would then be checked. Any thoughts on this would be appreciated as I begin to figure this out. -
Does Python RQ or Django RQ use Multiple Processors?
I use Python RQ daily on an EC2 instance. One of the challenges my team is facing is that our team is relatively young in the Python space and unfamiliar with multithreading and multiprocessing. Currently we do everything on one core for a given request. Does Python RQ (and by extension Django RQ, the specific library we use), use multiprocessing? Does it use multiple cores? If not, is there a way we can achieve this? Should we set the number of workers to be the number of cores we have? -
'access_token' KeyError within django-slack-oauth
I am having difficulties while using the [django-slack-oauth][1] package. I am getting the error KeyError: 'access_token'. Apparently it is within the pipelines.py file of the package (see below). My goal is to enable my slack app to be installed by a wide public audience. File "venv/lib/python3.8/site-packages/django_slack_oauth/pipelines.py", line 38, in slack_user slacker.access_token = data.pop('access_token') KeyError: 'access_token' Is anyone able to help me debug this? -
It shows error 404 using python manage.py run server
Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: ^admin/ The current path, new_topic/, didn’t match any of these. -
How to link to external wepage with form HTML?
The links contained in the form normally display correctly not in the form but in the form every time I click the button I get a forbidden access error. Is the HTML correct? Is there a way around this? {% for v in owner_obj %} <div class="container"> <form action="{{ v.Link }}" method="POST" type="submit"> <button style="border: none;"> {% csrf_token %} <input type="hidden" name="tshirt_id" value="{{ v.id }}" /> <a href="{{ v.Link }}" rel="noopener noreferrer"> <img src="{{ v.Images }}" width="150" height="150"> </a> </button> </form> <figcaption> {{ v.Titles }} </figcaption> <figcaption> <b>{{ v.Prices }}</b></figcaption> </div> {% endfor %} -
Swagger does not reflect correctly POST endpoint definition in Django Rest Framework
I have a small endpoint class SmallEndpointViewSet(APIView): def post(self, request, *args, **kwargs): //add the request.data data to the db def delete(self, request, pk, format=None): // remove the data[pk] from db in urls.py urlpatterns = [ url( r'^small-endpoint/(?P<pk>\d+)/$', mystuff_views.SmallEndpointViewSet.as_view(), name='small-endpoint' ), url( r'^small-endpoint/$', mystuff_views.SmallEndpointViewSet.as_view(), name='small-endpoint' ), ] Everything works correctly except that in swagger, the post appears as POST /small-endpoint/{id} instead of POST /small-endpoint/ A colleague told me that I need to send a paramater to as_view as this: url( r'^small-endpoint/$', mystuff_views.SmallEndpointViewSet.as_view({ 'post': 'create' }), name='small-endpoint' ), but then I receive the error TypeError: as_view() takes exactly 1 argument (2 given) I believe that APIView version of as_view doesn't receive parameters, and that is fine. What I really want is to swagger reflect correctly that the POST call does not need and id How can I do that?