Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to use data from a function as a field in Meta class
I've created a function in my serializers.py that call an external API and give me a dict back. How can I use the output from return downloads in the get_all_files as a field in class Meta? With my solution I've got the following error: Field name get_all_files.downloads is not valid for model Application. serializers.py class OsdSerializer(serializers.ModelSerializer): bands = BandSerializer(source='indice_to_use.needed_bands', many=True) satellite = SatelliteSerializer(source='indice_to_use.satellite_to_use') indice = IndiceSerializer(source='indice_to_use') # configuration url = 'https://earth-search.aws.element84.com/v0' # URL to Sentinel 2 AWS catalog collection = 'sentinel-s2-l2a-cogs' # search parameter startDate = '2021-04-10' endDate = '2021-04-12' location = [ 13.6677, 43.7232, 16.2605, 45.4522 ] def get_all_files(*bandss): bbox_search = Search( bbox=location, datetime=startDate+"/"+endDate, query={'eo:cloud_cover': {'lt': 50}}, collections=[collection], url=url, sort={'field': 'eo:cloud_cover', 'direction': 'desc'}, ) items = bbox_search.items() downloads = {} for i, item in enumerate(items): data = {} data['Product ID']= item.properties["sentinel:product_id"] data['Preview']= item.asset("thumbnail")["href"] data['Date']= item.properties["datetime"] data['Cloud cover']= item.properties["eo:cloud_cover"] for band in bandss: data[band] = item.asset(band)["href"] downloads[i] = data return downloads class Meta: model = Application fields = ['machine_name', 'name', 'description', 'indice', 'satellite', 'bands', 'get_all_files.downloads', ] -
How to join 2 routers in DRF. Not extend, join
I need to join 2 routers like that I got router that generates /course/<course_id> i got router that generates /lesson/<lesson_id> i need to combine this two urls to /course/<course_id>/lesson/<lesson_id> this is what i tried router = routers.SimpleRouter() router.register(r'courses', CourseViewSet) lesson_router = routers.SimpleRouter() lesson_router.register('courses/<int:id>/lessons', LessonViewSet) it does't work correctly. It works but only if the url is /courses/<int:id>/lesson/1 where <int:id> is string not mock -
Reverse for 'like' not found. 'like' is not a valid view function or pattern name
I'm trying to create a like button using ajax in my project. But it gives error : Reverse for 'like' not found. 'like' is not a valid view function or pattern name. Here's my code. View.py def like(request): blog = get_object_or_404(Blogs, sno = request.POST.get('blog_id')) is_liked = False if blog.likes.filter(username = request.user).exists(): blog.likes.remove(request.user) is_liked = False else: blog.likes.add(request.user) is_liked = True context = { 'is_liked' : is_liked, 'blog' : blog, 'total_like': blog.total_like(), } if request.is_ajax(): html = render_to_string('like_section.html',context,request=request) return JsonResponse({'form':html}) urls.py urlpatterns = [ path('',views.blogs, name='blogs'), path('blog/<int:id>/<str:slug>',views.showblog, name='showblog'), path('writeblog/',views.writeblog, name='writeblog'), path('publish',views.publishBlog, name='publishblog'), path('like',views.like, name='like'),] template <p> Likes : {{total_likes}} Like{{total_likes| pluralize}} </p> {% if is_liked %} <button type="button" class="btn" id="like" name="blog_id" value="{{blog.sno}}"><i class="fa fa-thumbs-up">Dislike </i></button> {% else %} <button type="button" class="btn" id="like" name="blog_id" value="{{blog.sno}}"><i class="fa fa-thumbs-up"> Like </i></button> {% endif %} <script> $(document).ready(function (event) { $('#like').click(function(){ var pk = $(this).attr('value'); const path = '{% url "like" %}'; $.ajax({ type: "POST", url: path, data : {'id':pk, 'csrfmiddlewaretoken':'{{ csrf_token }}'}, dataType:'json', success:function(event){ $('#like-section').html(resopnse['form']); console.log($('#like-section').html(resopnse['form'])); } }); }); }); </script> -
Nginx passes the websocket request to Gunicorn instead of Daphne
I am setting up a production server with nginx and Gunicorn+Daphne. Everything is working well except the ws proxy_pass. I followed this two tutorials. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-14-04 https://github.com/mitchtabian/HOWTO-django-channels-daphne etc/nginx/sites-aviable/multichats.conf server { listen 80; server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/vagrant/multichat; } location /ws/ { proxy_pass http://0.0.0.0:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } For some reason the websocket request is passed to Gunicorn instaed of Daphne: Apr 26 01:55:08 multichats gunicorn[16099]: Not Found: /chat/stream/ Apr 26 01:55:08 multichats gunicorn[16099]: - - [25/Apr/2021:23:55:08 +0000] "GET /chat/stream/ HTTP/1.0" 404 2307 "-" "Mozilla/5.0 (Windows NT 10.0; nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; ## # Gzip … -
Lock web page in Django admin if another user in that page
I'm new to Django. I'm looking for a way to lock a custom template in the Django admin for accessing more than 1 user at a time. Is there a way to do it with Sessions? Or do it with javascript? Thanks in advance! -
How To Migrate IntegerField To ForeignKey
I have a legacy database I am migrating towards Django. I have model like this: class MyModel(models.Model): other_id = models.IntegerField() This is an existing table filled with valid data. I want to migrate to class MyModel(models.Model): newbie = models.ForeignKey( OtherModel, on_delete=models.CASCADE, db_constraint=False, db_column="other_id", ) However, the generated migration keeps insisting on adding the already existing field and than dropping it: python manage.py sqlmigrate app 0069 BEGIN; -- -- Add field -- ALTER TABLE `mymodel` ADD COLUMN `other_id` integer DEFAULT 1 NOT NULL; ALTER TABLE `mymodel` ALTER COLUMN `other_id` DROP DEFAULT; -- -- Remove field -- ALTER TABLE `mymodel` DROP COLUMN `other_id`; Is there a way to convince Django to treat the field as ForeignKey without this exercise? I'd like to avoid a need to --fake the migration. -
Strange issue when calling same piece of code in multiple places in one template
I am facing a strange issue. I have two method in a model. get_delivery_taxes and get_subtotal_taxes as shown below: def get_delivery_taxes(self): delivery_tax_list = [] if self.modifiers: if self.modifiers.get('Taxation', None): for tax in self.modifiers.get('Taxation'): if tax.get('delivery_tax', None): delivery_tax_dict = tax.get('delivery_tax') delivery_tax_amount = delivery_tax_dict['amount'] delivery_tax_dict['amount'] = Money(delivery_tax_amount, settings.DEFAULT_CURRENCY) delivery_tax_list.append(delivery_tax_dict) return delivery_tax_list def get_subtotal_taxes(self): subtotal_tax_list = [] if self.modifiers: if self.modifiers.get('Taxation', None): for tax in self.modifiers.get('Taxation'): subtotal_tax_dict = None if tax.get('subtotal_tax', None): subtotal_tax_dict = tax.get('subtotal_tax') subtotal_tax_amount = subtotal_tax_dict['amount'] subtotal_tax_dict['amount'] = Money(subtotal_tax_amount, settings.DEFAULT_CURRENCY) subtotal_tax_list.append(subtotal_tax_dict) return subtotal_tax_list Those two methods are then used by these below methods to calculate their totals. def get_subtotal_tax_price(self): subtotal_tax_price = 0 for sub_tax_price in self.get_subtotal_taxes(): subtotal_tax_price = subtotal_tax_price + sub_tax_price['amount'] return subtotal_tax_price def get_delivery_tax_price(self): delvry_tax_amount = 0 for del_tax_price in self.get_delivery_taxes(): delvry_tax_amount = delvry_tax_amount + del_tax_price['amount'] return delvry_tax_amount A final total is calculated using above two methods as below. def get_order_final_total(self): subtotal = self.get_order_subtotal_price() subtotal_taxes = self.get_subtotal_tax_price() devilery_charges = self.get_order_delivery_charges_price() devilery_charges_taxes = self.get_delivery_tax_price() order_total = subtotal + subtotal_taxes + devilery_charges + devilery_charges_taxes return order_total In my template, I use them as below: {% for tax_dict in object.get_delivery_taxes %} ... {% endfor %} {% for tax_dict in object.get_subtotal_taxes %} ... {% endfor %} {{object.get_order_final_total}} Doing this was working fine until I … -
How to get file from django-import-export?
I want to use groupby() function from pandas, but dont know how to get file before export. I've tried dehydrate, but I dont think it's what i want. phone = Field() class Meta: model = Phones # exclude = ('id', ) def dehydrate_url(self,phone): -
Django: How do I get referenced objects in a symmetric ManyToMany relationship?
I've created a Many-to-Many relationship for the model UserProfile, to enable users to grant access to a particular feature to one another. The relationship works as expected with the use of symmetrical=False to ensure a user access is one-way. Model from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField(blank=True, null=True) image = models.ImageField(upload_to='profile_image', default="default_thumbnail.jpg") department = models.ForeignKey(DepartmentModel, on_delete=models.SET_NULL, null=True) allow_booking_access = models.ManyToManyField("self", blank=True, symmetrical=False) def __str__(self): return self.user.username class UserInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'UserAccounts' class UserAccount(BaseUserAdmin): inlines = (UserInline,) I am able to query the users that a particular user wants to grant access to via: (for example id=1) UserProfile.objects.get(id=1).allow_booking_access.all() However, I would like to retrieve the users that have granted access to the particular user. How would I do this? -
Why is selenium not finding an element on a website
I have the following test that I want to run. A payment request is being made from my application. For the user to complete the payment they have to visit a link on a website that processes payments. I want selenium to enter the email address which is required to complete the payment. I am getting the following error. E ====================================================================== ERROR: test_submit_payment (order.tests.test_views.TestViewsLiveServer) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/patrice/django-apps/dropby/dropby/order/tests/test_views.py", line 222, in test_submit_payment username = self.selenium.find_element_by_id('username') File "/home/patrice/django-apps/dropby/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "/home/patrice/django-apps/dropby/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element 'value': value})['value'] File "/home/patrice/django-apps/dropby/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/home/patrice/django-apps/dropby/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="username"] Below is my code for the test. def test_submit_payment(self): # get the url to goto the payment view submission view url = self.live_server_url + reverse('order:payment', kwargs={'pk': self.order.pk}) self.selenium.get(url) # self.selenium.find_element_by_xpath("//select[@name='method_of_payment']/option[text()='ecocash']").click() phone_number_input = self.selenium.find_element_by_name('phone_number') phone_number_input.send_keys('0777777777') # Submit the form submit_button = self.selenium.find_element_by_id("submit-payment") submit_button.click() # Now find the url that goes to the paynow website to complete a payment complete_payment_url = self.selenium.find_element_by_id('complete-payment-url') complete_payment_url.click() # Now we are on the paynow website, enter in the email address of the user who is going … -
Why is Django API Get working but Post not working?
I'm using Django to develop an API, the GET method works but the post method gives "Failed to Add." error. Following is the model, class Video(models.Model): VideoId = models.AutoField(primary_key=True) VideoName = models.CharField(max_length=100) FPS = models.CharField(max_length=100) TotalFrame = models.CharField(max_length=100) Duration = models.CharField(max_length=100) The API, @csrf_exempt def videoApi(request, id=0): if request.method == 'GET': video = Video.objects.all() video_serializer = VideoSerializer(video, many=True) return JsonResponse(video_serializer.data, safe=False) elif request.method == 'POST': video_data = JSONParser().parse(request) video_serializer = VideoSerializer(data=video_data) if video_serializer.is_valid(): video_serializer.save() return JsonResponse("Added Successfully!!", safe=False) return JsonResponse("Failed to Add.", safe=False) elif request.method == 'PUT': video_data = JSONParser().parse(request) video = Video.objects.get(VideoId=video_data['VideoId']) video_serializer = VideoSerializer(video, data=video_data) if video_serializer.is_valid(): video_serializer.save() return JsonResponse("Updated Successfully!!", safe=False) return JsonResponse("Failed to Update.", safe=False) elif request.method == 'DELETE': video = Video.objects.get(VideoId=id) video.delete() return JsonResponse("Deleted Succeffully!!", safe=False) URLs url(r'^video/$',views.videoApi), url(r'^video/([0-9]+)$',views.videoApi), serializers , class VideoSerializer(serializers.ModelSerializer): class Meta: model = Video fields = '__all__' JSON Input [{"VideoId": 2, "VideoName": "lol", "FPS": "1", "TotalFrame": "1", "Duration": "1"}] output , "Failed to Add." -
NoReverseMatch at / Reverse for 'product_detail' with arguments '(1, 'sgm')' not found. 1 pattern(s) tried: ['(?P<category_slug>[-a-zA-Z0-9_]+)$']
I'm learning Django framework and I have in the extend templates part, Error during template rendering,i have received this error.When i add slug field we get template error NoReverseMatch at / Reverse for 'product_detail' with arguments '(1, 'sgm')' not found. 1 pattern(s) tried: ['(?P<category_slug>[-a-zA-Z0-9_]+)$'] from django.urls import path from shop import views app_name='shop' urlpatterns = [ path('', views.product_list, name='product_list'), path('search', views.product_search, name='product_search'), path('<slug:category_slug>', views.product_list, name='product_list_by_category'), path('<slug:slug>', views.product_detail, name='product_detail'), ] {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>{% block title %}online shop{% endblock %}</title> <link rel="shortcut icon" type="image/png" href="{% static 'img/save.ico' %}"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <script src="{% static 'vendor/jquery/jquery.min.js' %}"></script> <script src="{% static 'vendor/jquery/custom.js' %}"></script> <script src="{% static 'vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <!-- Custom styles for this template --> <link href="{% static 'css/shop-homepage.css' %}" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-default navbar-fixed-top"> <div class="container"> <a href="/"> <img src="{% static "img/logo.png" %}" height="30px"></a> <button class="navbar-toggler" type="button" … -
Retrieve and Manipulate media files in Django
I am making a system, where I will let users upload excel files, and then I am saving the file to the 'media' folder. I am able to do it till this stage. Next, I want to be able to read the excel file, update its values/ add new columns/ add new rows, etc and then save the file and let the user download it. I am new to Django, and not able to do it. Can anyone help Here is the code, I used for uploading the file in the 'views.py' file def index(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] # print(uploaded_file.size) # print(uploaded_file.name) path = settings.MEDIA_ROOT print(path) # print(uploaded_file.content_type) fs = FileSystemStorage() name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) return render(request, 'index.html', context) -
Modelserializer related to users model
i have a model serializer which will create a post, and this post should be related to the user posting it, why this dont work ? class PostSerializer(serializers.ModelSerializer): class Meta: model = Posts fields = ('title', 'image') def create(self, validated_data): request = self.context.get('request', None) if request: user = request.user userobj=User.objects.get(username=user) post = Posts.objects.create(user=userobj, **validated_data) post.save() return user error message : AttributeError: 'User' object has no attribute 'title' -
Decoding (and equating) special characters with the Django REST framework SearchFilter?
I have implemented a Django Rest Framework SearchFilter in my backend, which for the most part works correctly. This is the code structure in views.py: class JobsViewSet(viewsets.ModelViewSet): queryset = Jobs.objects.all() serializer_class = JobSerializer filter_backends = [filters.SearchFilter] search_fields = ['^name', '^job_type'] The only remaining problem is that when sending get requests with a special character, for example the Swedish letter å, Django doesn't recognize that å is the same letter as Å only in lower case (as it does with for example a and A). In the GET calls from the front end, å gets converted to %C3%A5 for lowercase and %C3%85 for uppercase. This results in the search box not finding the jobs beginning with the letters åäö if the job title begins in uppercase (as in Återvinning). Does anyone know of a solution that makes the filter understand and equate uppercase and lowercase letters of special characters? Something along the lines of UTF-8 decoding? I have looked for answers both in the REST framework documentation and here on Stack Overflow, without any luck. New to Stack Overflow btw, I hope I'm doing the formatting correctly! -
not able to POST required data in django templates
I want to POST a form from my html to views.py in django, but I am not able do it. This is my html. This form should post the url of the downloaded image to the views.py function. {% for x in photo %} <a class="down" href="{{x.image.url}}" onclick="myfunc()" download="none">get</a> <form action="/image_info/" method="POST" id='dform'> {% csrf_token %} <input name='d_button' type="hidden" value="{{x.image.url}}"> </form> {% endfor %} This is my javascript function to submit form whenever the get link is pressed <script type="text/javascript"> function myfunc() { document.getElementById("dform").submit(); console.log('hello'); } </script> this is my views.py. This should take the image url from the form and display it in the new page. def show_image(): image_url = request.POST.get('d_button', None) return render(request, 'show_image.html', {'image': image_url) but my problem is that the form is not returning the url of the image that is clicked instead it is returning the url of first link. for example link1 link2 link3 link4 if I click on link3, it is downloading the image in link3 but POSTING the url of link1 This is a bit tricky to explain but this is the best I can. Thanks in adavnce. -
Django ORM taking long time to load
fund_df = pd.DataFrame(list(FundRolling.objects.filter(code__exact=str(code), rolling=rolling, start_date__gte=start_date, end_date__lte=end_date).values())) I have the above line of code in my views.py file. FundRolling is a model created in Django from MYSQL database. This model is having nearly 1 crore entries. This line is taking 20 seconds for execution. But I want it to reduce to milliseconds. What should I do? Thanks in advance. -
Django model field with a regex validator not working
The below model has a regex validator, however, when creating new objects (with standard model instantiation and model.objects.create() ), there is no error message given when creating an object that violates the validator. It allows the object to be saved. Below is the code for the model: class Area(models.Model): area = models.CharField(max_length=6, validators=[RegexValidator( regex='^[A-Z]{1,2}[0-9][A-Z0-9]?$', message='Area is not in correct format', code='invalid_area' )]) Any advise would be much appreciated. -
django-background-tasks not working with django-hosts
django-background-tasks package does not work when django-hosts package is configured. My background task function looks something like this: @staticmethod @background(queue="text") def sendMessage(phone_number, message): I am running this function on a specific queue. Also background task command is running too. python3 manage.py process_tasks --queue text My hosts configuration works properly. But not background tasks. When I remove hosts configuration background task function executes. -
data not pre populating in form when updating model data in DJANGO
I'm not sure what is going wrong but the data from the user is not pre populating into the form, even after following the django documentation, I'm only getting a empty form , in the url I have the correct id for the item , I have text and 2 'filefields' that i need to request into the update form and want the user to be able to update one or more of the fields , appreciate the help ? here are my views and updateform html views @login_required def music_upload(request, slug): if request.method == "POST": form = MusicForm(request.POST, request.FILES) if form.is_valid(): song = form.save(commit=False) song.artist = request.user song.track = request.FILES['track'] file_type = song.track.url.split('.')[-1] file_type = file_type.lower() if file_type not in MUSIC_FILE_TYPES: messages.error(request, f'ERROR - Track needs to be in MP3 format, Please try again!') return render(request, 'feed/music_upload.html', {'form':form}) else: song.save() messages.success(request, f'Track Uploaded') return redirect('my_profile', slug=slug) else: form = MusicForm() return render(request, 'feed/music_upload.html', {'form':form}) @login_required def edit_song(request, pk): artist = request.user.profile.user_id track = Music.objects.get(pk=pk).artist if request.method == 'POST': m_form = MusicUpdateForm(request.POST, request.FILES, instance=track) if m_form.is_valid(): m_form.save() messages.info(request, f'Your track has been updated!') return redirect('edit_track') else: m_form = MusicUpdateForm(instance=track) context ={ 'm_form': m_form, 'track': track, 'artist': artist, } return render(request, … -
Django many to many field, but display just the highest value
I want to know how I can display the highest ranking from the model education in the staff. The user would be able to select all of their educations, but for me it's irrelevant to know if the the user selected "high school" when he/she also has a master's degree. class Staff(models.Model): education = models.ManyToManyField('Education', verbose_name = 'Education') class Education(models.Model): name = models.CharField(max_length = 200, blank = False) rank = models.PositiveIntegerField(default = 0) def __str__(self): return self.name I gave every type of education a ranking. So in the Admin, the only thing I want returned would be the highest eduacation by a member of the staff - how do I write this function? class StaffAdmin(admin.ModelAdmin): list_display = ('rank') -
Error [{'error': 'NotRegistered'}] while using FCMNotification in python
I am getting the below error while running the snippet , even I tried uninstalling the app and login again, but no luck (using django REST as backend) Error msg {'multicast_ids': [5963190568359198474], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'NotRegistered'}], 'topic_message_id': None} code def send_notification_multiple_devices(device_ids=None, data=None): push_service = FCMNotification(api_key=FIRE_BASE_KEY) result = [] for id in device_ids: try: resp = push_service.notify_single_device( registration_id=id, message_title=data["title"], message_body=data["desc"], data_message=data, extra_notification_kwargs=extra_notification_kwargs, content_available=True, ) result.append(resp) except: pass return result -
AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)
i'm trying to test admin and getting AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200) even i check the solution over here but i already did the same and getting same error. My model file, admin file, and Testing file are below. admin.py from django.contrib import admin # Register your models here. from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from . import models class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display = ['email', 'name'] admin.site.register(models.User, UserAdmin) tests/test_admin.py from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_user( email = 'admin@admin.com', password = 'admin' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email = 'test@londondevapp.com', password = 'Test@123', name = 'Test 1' ) def test_user_listed(self): """Test that users are listed on user page""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) -
Not able to get image from django rest framework url
I've setup my django rest framework server in which I want to upload some news alongside their images. Actually I'm able to upload news and images because I retrieve them on my server filesystem, but when I request for a list of news I get an image url which, when pasted in my browser, shows me "The requested resource was not found on this server". Following is reported some code. models.py class News(models.Model): author = models.CharField(max_length=50) title = models.CharField(max_length=150) content = models.CharField(max_length=10000) image = models.ImageField(upload_to='news', blank=True, null=True) created = models.DateField(auto_now_add=True) def __str__(self): return "{}".format(self.title) serializers.py class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = '__all__' settings.py MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') views.py class GetNews(generics.ListAPIView): queryset = News.objects.all() serializer_class = NewsSerializer def post(self, request): author = request.data['author'] title = request.data['title'] content = request.data['content'] try: image = request.data['image'] except KeyError: raise ParseError('Request has no resource file attached') news = News.objects.create(image=image, author=author, title=title, content=content) return Response("News successfully uploaded.", status=status.HTTP_200_OK) def delete(self, request): token = request.META.get('HTTP_AUTHORIZATION') if not check_token(token): return JsonResponse({'message': 'Unauthorized!'}, status=status.HTTP_401_UNAUTHORIZED) news = News.objects.get(id=request.data['id']) news.delete() return JsonResponse({'message': 'News was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT) urls.py urlpatterns = [ ... path('news', views.GetNews.as_view()) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django Bootstrap will not let me center this container
I have been trying to center this div container after my navbar so that there is an equal space on both sides of the page. But, it is not working for some reason. Can you guys help please? The post_job.html is the issue. The portion where i display the text is being rendered on the left side with a bit of text going down Here is my code snippet: post_job.html {% load static %} {% include 'recruiter_navigation.html' %} {% block content %} <div class="row"> <div class="col-lg-2 col-md-2 col-sm-12 col-xs-12 hidden-xs hidden-sm full_width"> <h2 style="color: darkblue;" class="text-center">Post an Internship</h2> </div> </div> {% endblock content %} recruiter_navigation.html <div class="container"> {% block content %} {% endblock content %} </div>