Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how use setUp in selenium webdriver remote?
I want to use setUp instead of setUpClass in my selenium tests. This code works fine and is able to get the correct host when using setUpClass: @tag('selenium') @override_settings(ALLOWED_HOSTS=['*']) class BaseTestCase(StaticLiveServerTestCase): """ Provides base test class which connects to the Docker container running selenium. """ host = '0.0.0.0' @classmethod def setUpClass(cls): super().setUpClass() cls.host = socket.gethostbyname(socket.gethostname()) cls.selenium = webdriver.Remote( command_executor='http://selenium_hub:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME.copy(), ) cls.selenium.implicitly_wait(15) How should I do it if I'm gonna use setUp? @tag('selenium') @override_settings(ALLOWED_HOSTS=['*']) class BaseTestCase(StaticLiveServerTestCase): """ Provides base test class which connects to the Docker container running selenium. """ host = '0.0.0.0' def setUp(self) -> None: super(BaseTestCase, self).setUp() self.selenium = webdriver.Remote( command_executor='http://selenium_hub:4444/wd/hub', desired_capabilities=DesiredCapabilities.CHROME.copy(), ) self.host = socket.gethostbyname(socket.gethostname()) self.selenium.implicitly_wait(15) -
Documentation tool - Search into HTML files from django templates
I am working on a website using django. I have a documentation section with plain HTML files (i.e. not related to the django databases, just text). Those files have been converted from LaTeX to HTML. I would like to add a search bar into my documentation so the user can search a word to get some kind of help, for example by: highlighting the word in the text, returning a list of urls of the pages where the word occur, telling me how many times this word occur in each section of the table of content, ... I've been searching on the web for a while be could not find anything on how I could do this. I would appreciate any help/tips. Thanks in advance. -
Reverse for 'post_list' with keyword arguments '{'pk': 20}' not found. 1 pattern(s) tried: ['$']
I'm getting this NoReverseMatch error with pk 20 even when i have created only one post in the database. It doesn't the list all the posts as it should do and it gives this error. [enter image description here][1] This is the screen shot [1]: https://i.stack.imgur.com/GoqyT.png models.py from django.db import models from django.urls import reverse from django.utils import timezone # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=100) text = models.TextField() created_on = models.DateTimeField(default=timezone.now) published_on = models.DateTimeField(blank=True, null=True) def publish(self): self.published_on = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approve_comment=True) def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) # def __str__(self): # return self.author def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=100) text = models.TextField() created_on = models.DateTimeField(default=timezone.now) approve_comment = models.BooleanField(default=False) def approve(self): self.approve_comment = True self.save() def get_absolute_url(self): return reverse("post_list") # def __str__(self): # return self.text def __str__(self): return self.text urls.py from django.urls import path from blog import views urlpatterns = [ path('', views.PostListView.as_view(), name='post_list'), path('post/<int:pk>/', views.PostDetailView.as_view(), name='post_detail'), path('post/new/', views.PostCreateView.as_view(), name='post_new'), path('post/<int:pk>/delete/', views.PostDeleteView.as_view(), name='post_delete'), path('post/<int:pk>/update/', views.UpdatePostView.as_view(), name='post_update'), path('draft/', views.DraftListView.as_view(), name='post_draft_list'), path('post/<int:pk>/publish/', views.PostPublish, name='post_publish'), path('post/<int:pk>/comment/', views.add_comment_to_post, name='comment_new'), path('comment/<int:pk>/approve/', views.comment_approve, name='comment_approve'), path('comment/<int:pk>/remove/', views.remove_comment, name='comment_delete') ] views.py(only the list view) class PostListView(ListView): model = Post … -
how to merge django urls for GET and POST
I need help, I got a path() issue when I was trying route GET/POST request on a single url: When I want to add a server recored, I would do a POST {"serverid":1,"hostname":"test server"} on the url: /api/server/ but sometime I'd like to query the server by serverid, then I had to write another path() mapping for GET: /api/server/<int:serverid>/ Obviously they both can be in one view class/method, I believe this is more duplicated, but how can I merge these two url into one path? Thanks for your help. -
How to set dynamic or any caching in Django+Gunicorn+Nginx?
Ultimately I want my webapp to automatically detect changes in static files and serve the new ones, but even setting a cache policy successfully in Nginx would do at the moment. I tried several approaches: including expires: off;, expires: 1h; in my sites-enabled/projectname file, also including this inside and outside the scope location {...}, none of it worked. I tried to check with curl -I https://mywebsite, but no information about cache policy was returned either times. (I also restarted nginx after each change.) The file: server { listen 443 ssl http2; ssl on; ssl_certificate /home/name/ssl/sitename/certificate.crt; ssl_certificate_key /home/name/ssl/sitename/private.key; server_name sitename; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/name/projectname; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } Currently this is what curl gives back: HTTP/2 405 server: nginx/1.10.3 (Ubuntu) date: Mon, 27 Jul 2020 15:10:26 GMT content-type: text/html; charset=utf-8 content-length: 0 allow: GET x-frame-options: DENY vary: Cookie x-content-type-options: nosniff Any help is much appreciated! -
Django server not running in LAN
I'm trying to access my Django server with my phone in the local network. It used to work fine until my router was changed and now my server can only be accessed from the same maschine, which is weird. I tried the following: Added my private IP (ipconfig > WIFI-3 LAN adapter > ipv4) = 192.168.0.23 to ALLOWED_HOSTS Ran python manage.py 0.0.0.0:8000 Then tried to access the url http://192.168.0.23:8000 from my phone But I get a timeout error and no response. When i access the same URL from my maschine, it works just fine. I also tried running python manage.py runserver 192.168.0.23:8000, but got the same result. I made sure that I was working in the same network. What am I missing here? -
Setting up a Two Tiered User System in Django
I'm pretty new with Django. I'm building my first app using the framework: a simple blog. I want to implement two different types of users: an ordinary user who can only comment on posts, and an admin user who can both comment on posts and create posts. my current set up is as follows: models.py: User = get_user_model() class Author(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) profile_picture = models.ImageField() def __str__(self): return self.user.username right now once logged in a user can do everything. From reading the following documentation: https://docs.djangoproject.com/en/2.2/topics/auth/default/#groups , https://docs.djangoproject.com/en/3.0/topics/auth/customizing/#extending-user . I think the way to do that would be with with different user groups, but like I said I'm new at this. My question is essentially what is the best / simplest configuration I can use to enable a two user system? Also on a side note while reading through the docs I saw a section saying that if you're starting a new project it's highly recommended to set up a custom user model. I didn't do this. I only have two users in the system currently: myself as a super user, and a test user. Can I just delete the test user and then create a custom user class? -
Can I see what is happening in the django admin side?
Is it possible with Django to have an overview of what is happening when I set an object with the admin interface ? Because I want to give ability to an admin to set some objects, then I want that some modifications automatically impact other objects. But I can't find where a the files or where are the functions called by the admin interface. I looked into admin.py but it allows me to filter, exclude or display some fields, no interest for my problem. Have you an idea how to see what is happening in admin side please ? Thank your for reading -
A HTTP 404 with get/static
I got a GET HTTP 404 when I ran my Django page. The goal is to get an arrow showing a dropdown list to log me out when I click on it. I followed the tutorial on https://simpleisbetterthancomplex.com/series/2017/09/25/a-complete-beginners-guide-to-django-part-4.html#displaying-menu-for-authenticated-users It says GET static/js/bootstrap.min.js HTTP/1.1 404 1683 I need to know why I am getting this error. Can anyone show me how to fix this? -
When in uje {% for loop %} in html js doesnt work django
js code in base.html. When i use loop in html first box work but second box doesn't work I add script code this file in side even so doesn't work How i can do it? {% for photos in x %} {% with a=photos %} <div class="row"> <div class="col-xl-12"> <div id="panel-1" class="panel"> <div class="panel-hdr"> <h2> {{ a }} <span class="fw-300"><i>Example</i></span> </h2> <div class="panel-toolbar"> <button class="btn btn-panel" data-action="panel-collapse" data-toggle="tooltip" data-offset="0,10" data-original-title="Collapse"></button> <button class="btn btn-panel" data-action="panel-fullscreen" data-toggle="tooltip" data-offset="0,10" data-original-title="Fullscreen"></button> <button class="btn btn-panel" data-action="panel-close" data-toggle="tooltip" data-offset="0,10" data-original-title="Close"></button> </div> </div> <div class="panel-container show"> <div class="panel-content"> <div id="js-lightgallery"> {% for photo in post %} {% if photo.ders == a %} {% if photo.img %} <a class="" href="{{photo.img.url}}" data-sub-html="{{photos.title}}"> <img class="img-responsive" src="{{ photo.img.url }}" alt="{{photo.title}}"> </a> {% endif %} {% endif %} {% endfor %} -
Django Online Market Models
Hello. I'm new to Django and want to do a project. I have some models that need to be fix. It's Online Shop and I have already done them but I'm not sure how many of them are correct. The main problem is Order and OrderRow which I think needs some changes. I explain each one of them below 1- Order.total price. I'm not sure about it. 2- Order.row I need to be able to see all objects in 'OrderRow' and the problem is when i want to save an order I need to fill 'order' object that has a foreign key to 'OrderRow' and when I want fill it I need to fill 'OrderRow.order' which is not completed. one of them I think need to be null but I'm not sure which one. 3-The rest parts, need to be done with staticmode. A: def initiate(customer) This function check if the customer has an order before or not, if he has, we must return his order and if he doesn't have, we should create a new order for him. B: def add_product here, we should add a specific product and amount to OrderRow list. I need to check if the … -
I'm getting a JSON Decode error after successfully updating a resource
I'm getting the following at after updating an index schema on the azure portal. JSONDecodeError at /updateIndex/ The schema is successfully updating, but I'm get this error along with 500 status code. This is my function @csrf_exempt def updateIndex(request): url = 'https://search-test.search.windows.net/indexes/hotels-quickstar11t?api-version=2020-06-30' index_schema = { "name": "hotels-quickstar11t", "fields": [ {"name": "HotelId", "type": "Edm.String", "key": "true", "filterable": "true"}, {"name": "HotelName", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "true", "facetable": "false"}, {"name": "Description", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "false", "facetable": "false", "analyzer": "en.lucene"}, {"name": "Description_fr", "type": "Edm.String", "searchable": "true", "filterable": "false", "sortable": "false", "facetable": "false", "analyzer": "fr.lucene"}, {"name": "Category", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Tags", "type": "Collection(Edm.String)", "searchable": "true", "filterable": "true", "sortable": "false", "facetable": "true"}, {"name": "ParkingIncluded", "type": "Edm.Boolean", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "LastRenovationDate", "type": "Edm.DateTimeOffset", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Rating", "type": "Edm.Double", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "Address", "type": "Edm.ComplexType", "fields": [ {"name": "StreetAddress", "type": "Edm.String", "filterable": "false", "sortable": "false", "facetable": "false", "searchable": "true"}, {"name": "City", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "StateProvince", "type": "Edm.String", "searchable": "true", "filterable": "true", "sortable": "true", "facetable": "true"}, {"name": "PostalCode", "type": "Edm.String", "searchable": "true", "filterable": … -
Sole problems with Slug and Date Field problem in Django
I have a problem with Django code, I'm working with models to create an alternative post-creation page and the date wiget generated is a text-input. Also autocomplete not work for Slug. Someone can help me? models.py: from django.db import models from django import forms from django.contrib.auth.models import User from django.urls import reverse # Categorie class Category(models.Model): class Meta: verbose_name = 'category' verbose_name_plural = 'categories' name = models.CharField('Titolo', max_length = 250) slug = models.SlugField(max_length = 250, unique = True) desc = models.TextField('Descrizione', max_length=10000, blank=True) def __str__(self): return self.name # Articles class Article(models.Model): title = models.CharField('Titolo', max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE,) category = models.ForeignKey (Category, on_delete=models.CASCADE) desc = models.CharField('Descrizione', max_length=10000, blank=True, ) text = models.TextField('Testo', max_length=10000, blank=True) image = models.ImageField('Foto', blank=True, upload_to="img") data = models.DateTimeField('Data di pubblicazione', blank=True) slug = models.SlugField(max_length = 250, null = True, blank = True, unique=True) def get_absolute_url(self): return reverse("admin", args=(str(self.id))) class Meta: # Order post by date ordering = ['-data',] def __str__(self): return "Ciao" add_post.html: {% block content %} <h1>Add - Post</h1> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button> Go</button> </form> {% endblock content %} -
How to resume a method that sends a Django signal before the action in the signal handler terminates?
I have 3 models for Exchange, Market and Candle linked with Foreignkey relations. One of my methods do a for loop through all markets objects and creates new Candle objects. Now, as soon as a new object is created I need to check if the market is updated and do more stuff, so I decided to use Django signals. My problem is that when a post_save signal is triggered the for loop is paused until the end of the action in the signal handler is terminated. How could I bypass this? models.py class Exchange(models.Model): name = models.CharField(max_length=12, blank=True, null=True) def update_markets_price(self): for market in Market.objects.filter(exchange=self): # do stuffs Candle.objects.create(market=market, exchange=self, data=data) # Trigger post_save signal update = True class Market(models.Model): exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE, null=True) class Candle(models.Model): exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE) market = models.ForeignKey(Market, on_delete=models.CASCADE) data = JSONField(null=True) signal.py @receiver(post_save, sender=Candle) def my_handler(sender, instance, created, **kwargs): if created: while not updated: time.sleep(2) do_stuffs() # This is never executed because the for loop never ends For example here the while remains False because the for loop is in pause mode and it never terminates. I could find a solution for this very specific case but sometimes I need to let the … -
the production server does not have a file or an invalid directory django
the project has a function for generating qr code: class QrCreate(LoginRequiredMixin, View): def get (self, request, admission_id): eq = EquipmentWorker.objects.get(id=admission_id) return render(request, 'inventory/qr_detail.html',context={ 'eq': eq}) def post(self, request, admission_id): eq = EquipmentWorker.objects.get(id=admission_id) qr = False global data if request.method == 'POST': qr = True data = request.POST['data'] img = make(data) img.save("inventory/static/images/test.png") else: pass return render(request, 'inventory/qr_detail.html',context={ 'eq': eq, 'data': data}) path to qr-filetest.png -/home/user/dj/app/inventoryengine/inventory/static/images views.py path - /home/user/dj/app/inventoryengine/inventory gunicorn command = '/home/user/dj/inventory/bin/gunicorn' pythonpath = '/home/user/dj/app/inventoryengine' bind = '127.0.0.1:8001' workers = 5 user = 'user' limit_request_fields = 32000 limit_request_fields_size = 0 raw_env = 'DJANGO_SETTINGS_MODULE=inventoryengine.settings' nginx server { listen 80 default_server; listen [::]:80 default_server; root /var/www/html; index index.html index.htm index.nginx-debian.html; server_name _; location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; add_header Access-Control-Allow-Origin *; } on the local-manage.py server the function works, but on the production-gunicorn server it gives an error: [Errno 2] No such file or directory: 'inventory/static/images/test.png' -
Cancel Button in View leading to previous page
I tried to implement a cancel button via a mixin, but fail to get the correct URL. I want to go back to the page before the CreateView if the user presses "cancel" - if that should fail, I want the user to end up in index. views.py: class CancelButtonMixin(object): def post(self, request, *args, **kwargs): if "cancel" in request.POST: if request.META.get('HTTP_REFERER') != None: url = request.META.get('HTTP_REFERER' , '/') else: url = reverse_lazy("index/") return redirect(url) else: return super(CancelButtonMixin, self).post(request, *args, **kwargs) class SomeCreateView(CancelButtonMixin, CreateView): model = SomeModel template_name ="..." form_class = SomeFormsetName success_url = reverse_lazy('index/') forms.py: class SomeFormsetName(ModelForm): required_css_class = "required" class Meta: model = SomeModel fields = ("one", "two", "three", "four") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.layout = Layout(Row(Column(Field('one')), Column(Field('two', css_class='form-control')), css_class='form-row'), Submit('submit', 'Save price', css_class='btn-primary'), Submit('cancel', 'Cancel', css_class='btn-secondary', formnovalidate='formnovalidate'), Field("three", type="hidden"), Field("four", type="hidden")) my problem is that the url parameter holds exactly the url I am at, not the one from the previous page. How can I correct this behavior? url in my example will refer to http://127.0.0.1:8000/partprice_update/2 -
Google recaptcha not working on Django form framework
I am trying to follow this tutorial to load an invisible google recaptcha tag to my Django reset password form: https://medium.com/@mihfazhillah/how-to-implement-google-recaptcha-v3-on-your-django-app-3e4cc5b65013 Here's the full HTML of my attempt: {% extends 'base.html' %} {% block content %} {% load i18n static %} {% load crispy_forms_tags %} <script src="https://www.google.com/recaptcha/api.js?render=<MY SITEKEY HERE>"></script> <script> $('document').ready(function submitResetForm() { grecaptcha.ready(function () { grecaptcha.execute("<MY SITEKEY HERE>", {action: 'homepage'}).then(function (token) { $('input#id_recaptcha').val(token); }); }); }); </script> <div class="container" style="background-color:white;font-family:Roboto Condensed,Roboto,Charcoal, sans-serif" > <div class="row justify-content-center" style="margin-bottom:10; padding-bottom:10;"> <div class="col-md-4 pt-4"> <h2 class="text-center pb-1" style="font-size:large;font-weight:bold">RESET PASSWORD</h2> <div class="text-center row"> <p>Enter your email address below, and we’ll email instructions for setting a new one.</p> </div> <form id="reset-password-form" method="POST" class="form-group"> <div class="row"> {% csrf_token %} <div style="color:red;">{{ form.non_field_errors }}</div> <div class="form-group col-md-12"> {{ form.email|as_crispy_field }} </div> {{ form.recaptcha }} <div class="form-group col-md-12"> <input onclick="reCaptcha()" id="submit" type="submit" class="btn btn-primary btn-block" value="Reset password"> </div> </div> </form> </div> </div> </div> {% endblock %} Using the test codes supplied here: https://developers.google.com/recaptcha/docs/faq and below: Site key: 6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI Secret key: 6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe I was able to get a recaptcha tag on my webpage (with the warning message disclaimer). However I wasn't able to get any response in my form. When I replace these test keys with my real … -
Create method of Serializer class not getting called
I've viewset which has create method and my viewset is ModelViewSet. Serializer class also has create method which handles relationships manually. Ideally create from viewset should call create method of serialzier but it's not happening in my case. Using DRF from browser works like a charm for me but hitting endpoint from test fails it and from logs I can tell viewset create method is not calling create of serializer. I know perform_create has this logic serializer.save() but it's working when I try to hit via postman or browser DRF view but not working in case of tests: Here's my viewset: class MyViewSet(CacheResponseMixin, viewsets.ModelViewSet): permission_classes = (IsAuthenticated,) filter_backends = (DjangoFilterBackend,) def get_serializer_class(self): return serializer.MySerializer def create(self, request, *args, **kwargs): data = request.data.copy() context = {} self.prepare_and_set_read_only_data(data, context) serializer = serializers.MySerializer(data=data, context=context) serializer.is_valid(raise_exception=True) self.perform_create(serializer) # This doesn't trigger create method in case of tests but works fine in case of postman request headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Here's my serializer: class MySerializer(serializers.ModelSerializer): # all serializer fields . . . def create(self, validated_data): some_data = self.context.get('some_Data') instance = Model(**validated_data) instance.save() instance.some_data.set(some_data) instance.save() Here's my test: def test_create_using_api(self): response = self.client.post(self.list_path, self._instance_data(), format='json') program = Model.objects.last() assert response.status_code == 201 -
Django POST validated fields disappearing (NOT NULL constraint failed)
I have a Django project with some models. The one which is giving me trouble is this one: class Job(models.Model): patient = models.CharField(max_length=64, null=False, blank=False) how = MultiSelectField(choices=HOW_CHOICES, default=1) with_who = MultiSelectField(choices=WITH_WHO_CHOICES, default=1) accessories = MultiSelectField(choices=ACCESSORIES, null=True, blank=True) created = models.DateTimeField(auto_now_add=True, null=False, blank=False) scheduled = models.DateTimeField(null=True, blank=True) arrived = models.DateTimeField(null=True, blank=True) started = models.DateTimeField(null=True, blank=True) completed = models.DateTimeField(null=True, blank=True) scheduled_end = models.DateTimeField(null=True, blank=True) detected_end = models.DateTimeField(null=True, blank=True) approved = models.BooleanField(default=False) area_start = models.ForeignKey(Area, on_delete=models.CASCADE, null=False, related_name='jobs_start') area_end = models.ForeignKey(Area, on_delete=models.CASCADE, null=False, related_name='jobs_end') comment = models.CharField(max_length=256, null=True, blank=True) worker = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='jobs_worker') I have this URL to GET, POST, PUT and DELETE. router.register(r'jobs', views.JobList) The view linked to inherits from ModelViewSet: class JobList(LoginRequiredMixin, viewsets.ModelViewSet): queryset = Job.objects.all() serializer_class = JobsSerializer For my understanding, simply by inheriting from ModelViewSet the API handles GET, POST and PUT by default. That's probably why in the web API I see the form with the data to POST (see this screenshot). The view handles the GET perfectly, but the problem comes at the POST request. As you can see in the screenshot, there are only 3 fields to be filled for the POST data. But in the model I have more fields declared … -
Django Not Applying CSS File From App on 404 Page
Django 3.0.8 Python 3.7.x I've got a django project with a few apps. I'm trying to make some 'default' error pages for like 400, 403, 404, 500 errors. I've done that and the appropriate templates display - but without any styling or JS. In the 404 error page, I'm trying to link to the CSS from one of the apps so the correct styling gets applied - but in the console I see this error: Refused to apply style from 'http://127.0.0.1:8000/static/launcher/dist/css/launcher.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. The file exists there, however. That particular CSS file lives in two places: in the app directory and it also lives in the STATIC_ROOT because I ran the python manage.py collectstatic command. The STATIC_URL is set to /static/ The CSS file is located at: project_dir/launcher/static/launcher/dist/css/launcher.css project_dir/static/launcher/dist/css/launcher.css My 404 template lives at: project_dir/templates/404.html My link to the CSS looks like this: <link rel="stylesheet" type="text/css" href="{% static 'launcher/dist/css/launcher.css' %}" /> My project URL's look like this: urlpatterns = [ path("admin/", admin.site.urls), path("", include("launcher.urls")), path("app2/", include("app2.urls")), path("app3/", include("app3.urls")), path( "robots.txt", TemplateView.as_view( template_name="robots.txt", content_type="text/plain" ), ), path( "favicon.ico", RedirectView.as_view( url=staticfiles_storage.url("favicon.ico"), permanent=False ), name="favicon", ), ] … -
How to use Generic View for a child
I am starting to learn how to use the generic view. Considering that we`ve got a foreign key to parent. How can I create a child view using Generic View? Would that be the same way we are creating the parentview? views?.py class ChildCreateView(generic.CreateView): template_name = "app/create_child.html" model = Child form_class = ChildForm success_url = reverse_lazy("app:index_child") models.py class Parent(models.Model): pass class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) views1.py class ParentCreateView(generic.CreateView): template_name = "app/create_parent.html" model = Parent form_class = ParentForm success_url = reverse_lazy("app:index_parent") -
slack profile.set ignoring user in any case
I'm testing out slack integration with python, what I'm trying to do is update status of any user through api. I installed an app in my workspace & added permissions for user.profile.write & users:read & used SlackClient. The status update works fine but it is only updating the status of the person who created the app. You can find the profile.set api here which I'm using to set profile status, when I pass the user in params it is completely ignored, if I pass it in json as shown below then it throws an error saying invalid_user whereas same user is working perfectly in users.info api call. print(sc.api_call(api_method='users.info', params={'user':'U017KQ996KY'})) print(sc.api_call(api_method='users.profile.set', params={'user':'U017KQ996KY'}, json={ 'user': 'U017KQ996KY', 'profile': { "status_text": "on vacation", "status_emoji": ":airplane:" } } )) I'm at a loss here as to why this is happening, I even tried passing X-Slack-User with id in headers & that was ignored as well. It's either throwing an error or just changing status for the owner of the app. Any help or sense of direction is appreciated. -
How to hide POST form in Django REST framework?
I have a problem and I' hope someone could help me. I have Django REST framework form like this: and I would like to do a simple thing: hide POST form (in the red rectangle) when the user is not logged in. I just don't know how to do it, because all I have is model, view that inherits from ListCreateAPIView and serializer inhgeriting from ModelSerializer. -
How can I fix "bad interpreter" error after I renaming my django project in PyCharm?
I recently renamed my Django project in Pycharm and now I have many errors associated with Python. From my MAC terminal when I try and run: $ django-admin startproject mobileproject or $ pip install django I get: -bash: /usr/local/bin/pip: /usr/local/opt/python/bin/python3.7: bad interpreter: No such file or directory In Pycharm when I open most of my Django projects I now get: invalid python interpreter selected for the project Below was the original structure of my project: project ---project ---app ---models.py ...etc ---project ---settings.py ...etc ---manage.py ---venv To rename my Django project in Pycharm I right clicked on the root folder "project" and selected refactor/rename/rename project. For the rest of the folders I right clicked and selected refactor/rename and I was only given rename directory so I chose that. Below shows how I renamed my project folders. newproject ---newp ---newapp ---models.py ...etc ---newpp ---settings.py ...etc ---manage.py ---venv After doing this I have all the errors listed above. Even when trying to start a new project with django-admin startproject. I feel like the Python executable is in the wrong directory but I have no idea. Please Help! -
Data is not saved in database but primary key is created Django Fullcalendar
Currently actual data is not save in database but when ever register button is clicked after I input data, an empty data will be saved and primary key will be created. There is no error being posted anywhere but an empty data is saved. I'm using Django Framework for backend and as front-end, I mainly use Javascript and HTML. For database, I use Sqlite. I think the most important part in the data transport is in the Ajax part but since I just used Ajax and Javascript for the first time, I still don't know a lot of thing. Please help me. script.js function initializePage() { $('#calendar').fullCalendar({ height: 550, lang: "ja", header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay' }, navLinks: true, timeFormat: 'HH:mm', selectable: true, selectHelper: true, eventSources:[{ url: '/fullcalendar/calendar', method: 'GET', failure: function(){ alert("PROBLEM!!!"); }, } ], select: function(start, end, resource) { // 日付選択された際のイベント // ダイアログタイトル設定 $("#dialogTitle").text("スケジュール登録"); // タイトル初期化 $("#inputTitle").val(""); // 備考初期化 $("#inputDescription").val(""); // ボタン制御 $("#registButton").show(); $("#updateButton").hide(); $("#deleteButton").hide(); // ダイアログ表示 $('#inputScheduleForm').on('show.bs.modal', function (event) { setTimeout(function(){ $('#inputTitle').focus(); }, 500); }).modal("show"); // 日付ピッカーの設定 $('#inputYmdFrom').datetimepicker({locale: 'ja', format : 'YYYY年MM月DD日', useCurrent: false }); $('#inputYmdTo').datetimepicker({locale: 'ja', format : 'YYYY年MM月DD日', useCurrent: false }); $('.ymdHm').datetimepicker({ locale: 'ja', format : 'YYYY年MM月DD日 HH時mm分' }); // 開始終了が逆転しないように制御 …