Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Mobile screen size alias links not working
ROBLEM: In Mobile screen size alias links are not working Description I have built a project (HTML, CSS, JS building tool) with https://bootstrapshuffle.com/ I have exported the project Put it in to a django project I have added a few extra buttons to the middle of the screen that are fusions as alias on the landing page. ERORR: This exported project perfectly works with all the buttons when it is in Desktop screen size or tablet screen size (both cases the original builder reorganizes the components). But when I shrink the screen size to the size of a mobile and it reorganizes the components it leaves these alias buttons that worked in both tablet and desktop mode but does not in this mobile screen size. I have read the following projects and I probably have something similar Href links do not transpire/work at mobile size screen media queries not working on mobile screen size Links not working on site when screen size is reduced The only issue is that I have that the downloaded project from the online editor only given me a bootstrap.min.css and bootstrap.min.css.map non of them is organized. Is there a way to make them organized and … -
Django Rest Framework drf-nested-routers example of Infinite-depth Nesting and Hyperlinks for Nested resources
I am quite new to django-rest-framework. I am trying to combine the examples infinite-depth nesting and hyperlinks for nested resources in drf-nested-routers I added a MailReply object just to try the infinite-depth nesting. My infinite-depth nesting works fine but i am getting confused by the nesting serializer relations. models.py from django.db import models class Client(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class MailDrop(models.Model): title = models.CharField(max_length=100) client = models.ForeignKey('Client', on_delete=models.CASCADE, related_name='maildrops') def __str__(self): return self.title class MailRecipient(models.Model): name = models.CharField(max_length=100) mail_drop = models.ForeignKey('MailDrop', on_delete=models.CASCADE, related_name='mailrecipients') def __str__(self): return self.name class MailReply(models.Model): title = models.CharField(max_length=100) mail_recipient = models.ForeignKey('MailRecipient', on_delete=models.CASCADE, related_name='mailreplies') def __str__(self): return self.title I want to show the url of my objects like this, it's working but currently it's missing the url { "id": 1, "url": "/api/clients/2/" "name": "Client Name 1", "maildrops": [ { "title": "Mail Drop Title 1" } ] }, { "id": 2, "url": "/api/clients/2/" "name": "Client Name 2", "maildrops": [ { "title": "Mail Drop Title 2" } ] } I tried using NestedHyperlinkedModelSerializer instead of HyperlinkedModelSerializer in my custom serializers like what was suggested in the example for hyperlinks for nested resources both works. Also tried NestedHyperlinkedRelatedField instead of HyperlinkedRelatedField but like before it does the … -
Django app to perform Matrix operations [Beginner]
Design of the app. Click Here How can I make an app designed like this with Django? Please be detailed about the forms and I want the output to be displayed on the same page. -
cart added but is charged twice when checkout
I am having some issues with cart payment with stripe. When I checkout one product it is checking out two orders (no matter how many products I have within the cart). Here is the function I have to create a cart in session and error: from django.shortcuts import get_object_or_404 from tour_store.models import Destinations def cart_contents(request): """ Ensures that the cart contents are available when rendering every page """ cart = request.session.get('cart', {}) cart_items = [] total = 0 destination_count = 0 for id, quantity in cart.items(): destination = get_object_or_404(Destinations, pk=id) total += quantity * destination.price destination_count += quantity cart_items.append({'id': id, 'quantity': quantity, 'destination': destination}) #cart_item will loop into the cart. print(cart_items) print(destination_count) print(cart) return {'cart_items': cart_items, 'total': total, 'destination_count': destination_count} =====SHELL=============== {'1': 1} << NORMAL CART ADDED [11/Mar/2020 16:27:38] "GET /chekout/ HTTP/1.1" 200 12919 {'1': 1}. << DOUBLE THE CART AND CHARGE {'1': 1} [11/Mar/2020 16:28:59] "POST /chekout/ HTTP/1.1" 302 0 ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 54962) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in __init__ self.handle() File "/Users/macbook/software_projects/tour_project/venv/lib/python3.8/site-packages/django/core/servers/basehttp.py", line 174, in handle self.handle_one_request() File "/Users/macbook/software_projects/tour_project/venv/lib/python3.8/site-packages/django/core/servers/basehttp.py", line … -
authentication problem with django and apache wsgi
I want to have a base authentication into my django application by apache's base auth. my config looks like this: <IfModule mod_ssl.c> <VirtualHost *:443> ServerName url.test.com ServerAdmin webmaster@localhost.com ProxyPass / http://127.0.0.1:8000/ ProxyPassReverse / http://127.0.0.1:8000/ WSGIDaemonProcess projectname \ python-home=/home/user/app/project/env \ python-path=/home/user/app/project:/home/user/app/project/env/lib/python3.5/site-packages/ WSGIProcessGroup projectname WSGIScriptAlias / /home/user/app/project/app/server/wsgi.py WSGIPassAuthorization On Alias /static/ /home/user/app/app/project/static/ ErrorLog ${APACHE_LOG_DIR}/error-log CustomLog ${APACHE_LOG_DIR}/access-log combined LogLevel info # Protecting with basic authentication <Location /> AuthType Basic AuthName "Restricted Content" AuthUserFile /etc/apache2/.htpasswd Require user testuser AuthBasicProvider wsgi WSGIAuthUserScript /home/user/app/project/app/server/wsgi.py </Location> SSLCertificateFile /etc/letsencrypt/live/project.app.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/project.app.com/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> and wsgi.py containing: import os import sys sys.path.insert(0, '/home/user/app/project') sys.path.append('/home/user/app/project/env/lib/python3.5/site-packages') os.environ["DJANGO_SETTINGS_MODULE"] = "project.app.settings" from django.core.wsgi import get_wsgi_application application = get_wsgi_application() with this setup I get the error message: AH01618: user testuser not found: / after some research I've seen that I probably should remove AuthBasicProvider and WSGIAuthUserScript from Location to: # Protecting with basic authentication <Location /> AuthType Basic AuthName "Restricted Content" AuthUserFile /etc/apache2/.htpasswd Require user testuser </Location> this leads to the password being accepted, but then I get a 403 error in the django application: Forbidden: / [11/Mar/2020 17:23:35] "GET / HTTP/1.1" 403 13 as I'm usually more on the coding side I'm not super familiar with the setup of the django application … -
When does Django load the apps?
While messing around with signals I discovered that Django does not load the apps until some point after __init__.py runs. When does Django load the apps? Here is the code that led me here: __init__.py import imt_prod.signals signals.py from django.contrib.auth.signals import user_logged_in # This produces 'django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.' from imt_prod.models import LoginHistory def recordLogon(sender, user, request, **kwargs): from imt_prod.models import LoginHistory # This does not LoginHistory(User=user) user_logged_in.connect(recordLogon) models.py from django.contrib.auth.models import User from django.db import models class LoginHistory(models.Model): User = models.OneToOneField(User, null=False, blank=False, on_delete=models.SET("USER DELETED"), verbose_name="User") date = models.DateField(default=date.today, null=False, blank=False, verbose_name="Logon Date") -
Django : Can we send multiple POST requests using for loop in Django?
I am trying to send multiple POST requests using for-loop in Django, but the POST request work fine only for the first iteration, and for other iterations it gives 302 error. In the image below, a user can approve the project by checking the checkbox, however it works for 'MealBox' project and when someone tries to approve another project, he cannot do that and server gives 302 error. [![enter image description here][1]][1] views.py : @login_required def project_approval_by_mentor(request): faculty = FacultyInfo.objects.get(user = request.user) group = GroupInfo.objects.filter(mentor = faculty) my_project = [] for i in group: approved = False project = Project.objects.get(group =i) my_project.append(project) for i in group: approved = False project = Project.objects.get(group =i) if request.method == "POST": project_approval_by_mentor_form = ProjectApprovalByMentorForm(request.POST,instance = project) if project_approval_by_mentor_form.is_valid(): is_approved_by_mentor = project_approval_by_mentor_form.cleaned_data.get('is_approved_by_mentor') project.is_approved_by_mentor = is_approved_by_mentor project.save() approved = True return redirect("") else: return HttpResponse("NO response") else: project_approval_by_mentor_form = ProjectApprovalByMentorForm(instance = project) return render(request,'project_approval.html',{'my_project':my_project,'project_approval_by_mentor_form':project_approval_by_mentor_form}) template for the above views.py project_approval.html : {% block content %} <div align='center' class="container"> <br> {% if user.is_authenticated and not hod%} {% for project in my_project %} <form class="form-group" method="post"> {% csrf_token %} <h1>{{project.title}}</h1> <b><i>{{project.description}}</i></b> <br> {% if not project_approval_by_mentor_form %} <p>{{project_approval_by_mentor_form.as_p}}</p> <br> <input class=" btn btn-outline-success" type="submit" name="" value="Approve"> {% else … -
Django-password-reset logic
I got this error when I was trying to modify settings.py for password reset functionality for my website EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') -
Does memcache need to be started as a daemon separately when used with django?
I am trying to integrate caching with my django project. After some research I am convinced memcache is best for this. So, I require to install memcache through apt-get memcache and then its python bindings again as another apt-get python-memcache. Then, I need to include in settings.py: CACHES = { 'default':{ 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1;11211', } } My question is, all the tutorials follow upto this step. Is the above enough for setting up the cache? Do I need to do something to start memcache when running the project? If so, can I start memcache with python manage.py runserver command? -
One-To-Many Relationship Django
I am coding up a dictionary using Django. I want a word to have multiple definitions, if necessary. This would be a one-to-many relationship, but Django does not seem to have a OneToManyField. This is a snippet of my code: class Definition(models.Model): definition = models.CharField(max_length=64) class Word(models.Model): word = models.CharField(max_length=64, unique=True) definitions = models.ForeignKey(Definition, on_delete=models.CASCADE, related_name="word") I would like to do word.definitions and get back all the definitions of that word. Also, deleting a word should delete all definitions of that word. Finally, a_definition.word should give me the word associated with that definition. Help? -
Getiing this error-__init__() got an unexpected keyword argument 'instance'
im using a non-model based form django. once i get the data,i create a model object. but when im trying to edit my post(a blog/quote based app),im not able to create a form object using the model object for a specific post. these are my codes: views.py: def quote_form(request): if request.method=='POST': form=Quote(request.POST) if form.is_valid(): quote=form.cleaned_data['quote'] author=form.cleaned_data['author'] popularity=form.cleaned_data['popularity'] category=form.cleaned_data['category'] p=Quote1(quote=quote, author=author, popularity=popularity, category=category) p.save() return redirect("quote_list") else: form=Quote() return render(request,'quote/form.html',{'form':form}) def quote_edit(request, pk): q = get_object_or_404(Quote1, pk=pk) if request.method == "POST": form = Quote(request.POST,instance=q) if form.is_valid(): q = form.save(commit=False) q.author = request.user q.save() return redirect('quote_detail', pk=q.pk) #return render(request,"blog/post_detail.html",{'post':post}) else: form = Quote(instance=q) return render(request, 'quote/quote_edit.html', {'form': form}) models.py: class Quote1(models.Model): quote=models.CharField(max_length=200) author=models.CharField(max_length=200) popularity=models.IntegerField() category=models.CharField(max_length=40) forms.py: class Quote(forms.Form): quote=forms.CharField() author=forms.CharField() popularity=forms.IntegerField() category=forms.ChoiceField(choices=[('life','life'),('happiness','happiness'),('love','love'),('truth','truth'), ('inspiration','inspiration'),('humor','humor'),('philosophy','philosophy'),('science','science')]) -
Django on IIS: Debugging IIS Error due to FastCGI request timeout on large file upload
I'm trying to host a Django web application on a windows 10 machine with IIS 10 with FastCGI. Whilst everything is running good so far, I'm running into problems with certain POST-requests while uploading larger files (~120MB), namely an HTTP 500 Error. I'm at a point where I don't know how to debug any further. I resolved the Error "413.1 - Request Entity Too Large" by increasing the request limits. However, now I get an HTTP-error stating the following: C:\Apps\Python3\python.exe - The FastCGI process exceeded configured request timeout The timeout is set to 90 seconds, and I can tell that after the uploading of files completes, my browser is waiting about that time for a response from the server. There are not that much operations to perform within the Django-view for responding to the request. If I run the django developement server on the same machine, the response is beeing send justs seconds after the files were uploaded. The duration, the IIS takes to send the HTTP 500 response, takes more than 1 minute longer. I added some code to the Django-view in the post()-method to write something to a file whenever the method is called: def post(self, request, *args, … -
Django for desktop apps
I'm writing a desktop app with python. It's a client side. Can i use django framework for server side or are there any other frameworks that allow to develop servers for desktop apps? How can i send data to the server? I need to have an auth form, sessions perhaps and connection to mysql. Thanks for answers -
Modified “SM2+” Algorithm for Flashcard App Rating
I don’t know how to modify code for my adaptation of a flashcard app that uses an old algorithm to return flashcard data based on easiness rather than difficulty level, which returns a more precise result. According to the authors, the arguments should be changed as follows. The full calculation is displayed at the link below. I need your help in transforming the code to reflect the new algorithm. The Modified “SM2+” Algorithm http://www.blueraja.com/blog/477/a-better-spaced-repetition-learning-algorithm-sm2 Here is the new algorithm, with all the above improvements in place. For each review-item, store the following data: • difficulty:float – How difficult the item is, from [0.0, 1.0]. Defaults to 0.3 (if the software has no way of determining a better default for an item) • daysBetweenReviews:float – How many days should occur between review attempts for this item • dateLastReviewed:datetime – The last time this item was reviewed When the user wants to review items, choose the top 10~20 items, ordered descending by percentageOverdue (defined below), discarding items reviewed in the past 8 or so hours. After an item is attempted, choose a performanceRating from [0.0, 1.0], with 1.0 being the best. Set a cutoff point for the answer being “correct” (default is … -
Django_filters gives an error "QuizFilter has no len()"
I have one filter: import django_filters from .models import Quiz class QuizFilter(django_filters.FilterSet): class Meta: model = Quiz fields = ['title', 'level'] class QuizList(ListView): """List of quizzes + pagination""" model = Quiz template_name = 'quizapp/home.html' context_object_name = 'quizzes' paginate_by = 15 def get_queryset(self): qs = self.model.objects.all() filtered_quizzes = QuizFilter(self.request.GET, queryset=qs) return filtered_quizzes When I open the page I got this error: In templates I just write {% for quiz in quizzes.qs %} and for filtering I use {{ quizzes.form.as_p }} How can I solve the problem? -
Different forms with custom fields creating users in Django
I have two forms. One creates a Client and the other an Employee. The Client has a model Clients and is placed on the Clients group. The Employee is simply a user which is placed on the Employees group. This the Clients model: class Clients(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=200, verbose_name="Morada") city = models.CharField(max_length=200, verbose_name="Cidade") postal = models.CharField(max_length=8, validators=[RegexValidator(r'^\d{4}(-\d{3})?$')], verbose_name="Código Postal") nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], unique=True, null=True) mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')]) And this is the form used to create a client: class SignUpForm(UserCreationForm): address = forms.CharField(max_length=200, label="Morada", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Av. da Liberdade, 170',})) nif = forms.CharField(max_length=9, label="NIF", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Deve conter 9 dígitos',})) mobile = forms.CharField(max_length=9, label="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')], widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Deve conter 9 dígitos',})) city = forms.CharField(max_length=200, widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Lisboa',})) postal = forms.CharField(max_length=8, validators=[RegexValidator(r'^\d{4}(-\d{3})?$')], widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'0000-000',})) def clean_nif(self): nif = self.cleaned_data['nif']; if Clients.objects.filter(nif=nif).exists(): raise forms.ValidationError("NIF já existente.") return nif class Meta: model = User fields = ('username', 'password1', 'password2', 'email', 'first_name', 'last_name', 'address', 'nif', 'mobile', 'city', 'postal') def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) self.fields['username'].widget = TextInput(attrs={'class': 'form-control', 'placeholder': 'Utilizador do Cliente'}) self.fields['password1'].widget = PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Mínimo 8 caracteres'}) self.fields['password2'].widget = PasswordInput(attrs={'class': 'form-control', 'placeholder': 'Mínimo 8 caracteres'}) self.fields['first_name'].widget = TextInput(attrs={'class': 'form-control'}) self.fields['last_name'].widget = … -
Error with psycopg2 when execute runserver with DJANGO
I've been all morning trying to start my django project and it seems impossible, everytime I try to start it i get the next error: (venv) djimenez@TADEL-INF:/mnt/c/Users/djimenez/Desktop/bfl$ python bullfrogloader/manage.py runserver Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f04b7d7b6a8> Traceback (most recent call last): File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/psycopg2/__init__.py", line 126, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/core/management/base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 61, in applied_migrations if self.has_table(): File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 44, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 255, in cursor return self._cursor() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 232, in _cursor self.ensure_connection() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/backends/base/base.py", line 216, in ensure_connection self.connect() File "/mnt/c/Users/djimenez/Desktop/bfl/venv/lib/python3.6/site-packages/django/db/utils.py", line … -
Why the attributes of a object in __init__() and get_context_data() different?
class SomeView(DetailView) : def __init__(self, *kwargs): print(type(self), dir(self)) def get_context_data: print(type(self), dir(self)) __ init__ does not prints "request attribute" for dir(self), but get_context_data() prints. Why such a difference? -
405 Method not allowed on Django Form POST
everytime I click submit button on my POST form to upload a csv file. I get a code 405 Method not allowed. I already tried changing other importing methods like django_import_export but still get the same response (405). please help! This is my views.py: class AdvisoryView(TemplateView): template_name = 'advisory.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["adv"] = Mobile.objects.all() return context def mobile_upload(request): template = "advisory.html" prompt = { 'order': 'blah' } if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES('file') if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=',', quotechar='|'): _, created = Mobile.objects.update_or_create( mobile_owner=column[0], mobile_number=column[1], ) context = {} return render(request, template, prompt) and mobile.html look like this, I actually put the form inside a model form. <div class="modal-body"> {% block content %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file"> <p>Only accepts .csv file</p> <button type="submit">Upload</button> </form> {% endblock content %} </div> <div class="modal-footer"> and urls.py from django.urls import path, include from . import views from .views import AdvisoryView, HomeView urlpatterns = [ path('', HomeView.as_view(), name='home'), path('advisory/', AdvisoryView.as_view(), name='advisory'), ] -
Django static file 404
Everything works fine when I want to add an image from admin I can see my photo which is visible in the file path field. I am able to add my object but when it comes to running part, No image. "GET /static/static/images/python_logo.png HTTP/1.1" 404 1713 Models.py class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path='static/images') Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] and my folders -
Django Urls Corresponding With Jquery File
I am using Django with a Bootstrap template, that requires Jquery. But I am having trouble with a js file. I created static directory, and static_cdn directory. I am using a Bootstrap 4 template. My project template requires a js file (template doesn't working correctly without this js file) but this js file is not using a valid url; It is calling all my svg files, but with a nonvalid URL. This is my project static files folder : This is my urls.py urls : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^panel/$', panelView, name='panel'), url(r'^pageOne/$', pageOne, name='pageOne'), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is my settings.py : STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(os.path.dirname(BASE_DIR), "static"), # '/var/www/static/', ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") MEDIA_URL = '/evrak/' MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "evrak") This is my html page : <!-- BEGIN: Vendor JS--> <script src="{% static 'app-assets/vendors/js/vendors.min.js' %}"></script> <script src="{% static 'app-assets/fonts/LivIconsEvo/js/LivIconsEvo.tools.js' %}"></script> <script src="{% static 'app-assets/fonts/LivIconsEvo/js/LivIconsEvo.defaults.js' %}"></script> <script src="{% static 'app-assets/fonts/LivIconsEvo/js/LivIconsEvo.min.js' %}"></script> {% block vendorJS %} {% endblock vendorJS %} <!-- END Vendor JS--> <!-- BEGIN: Page Vendor JS--> {% block pageVendorJS %} {% endblock pageVendorJS %} <!-- END: Page Vendor JS--> Now, Django is able to load … -
Using external API for token based authentication in Django (DRF)
Context My API accepts a jwt-token that I can pass to an external endpoint which will return 401 if invalid/expired or user information if still valid. Based on this I will either return 401 or filtered data belonging to the user. Also, POST request's need to involve writing who this resource belongs to for the GET to work. I tried to do this by overriding the get_queryset and perform_create methods. My viewset looks something like this: class ReportViewSet(AuthorizedUserBasedFilteredViewset): queryset = Report.objects.all() serializer_class = ReportSerializer def perform_create(self, serializer): try: username = self.get_authorized_user()['user']['username'] except Exception as e: return Response({'error': 'Token does not exist'}, status=HTTP_401_UNAUTHORIZED) serializer.save(creatd_by=username) def get_queryset(self): try: username = self.get_authorized_user()['user']['username'] except Exception as e: return Response({'error': 'Token does not exist'}, status=HTTP_401_UNAUTHORIZED) return Report.objects.filter(created_by=username) This doesn't work because get_queryset expects a queryset as response. Questions How do I bubble up the authorize exception in get_queryset? Is there some other method I should be overriding to the authentication entirely? I still need to pass the username recieved to get_queryset for the authentication to be successful Is there a better way to do this? I looked at the RemoteUserAuthenticationBackend but that still involved creation of a User object but for this use case the … -
Python issues with form.cleaned_data.get('username')
When I submit my form, if valid, it should redirect me to my home page but it doesn't due to this line username = form.cleaned_data.get('username'), when I remove it works fine but then again I need that line to get the form data. Here's my code views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.forms import UserCreationForm def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') #Where the problem lies messages.success(request, 'Account created!') return redirect('home-page') else: form = UserCreationForm() return render(request, 'users/register.html', {'form': form}) I honestly can't figure out what's wrong with that line of code. I'm using Django v 3.0.4 btw -
Problem loading images from static in a .js file
scripts.js code: $(document).ready(function(){ $('#user').hover(function() { $('#user img').attr('src', "{% static 'images/user_selected.png' %}"); }, function() { $('#user img').attr('src', "{% static 'images/user.png' %}"); }); }); It works fine when I write it directly in my base.html file, but when I place it in an external .js file it fails to load images. Scripts.js file loads but images do not. base.html code: <head> ... <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="{% static 'js/scripts.js' %}"></script> ... </head> <body> ... <a href="{%url 'logout' %}">LOG OUT</a> <a id="user" href="#"><img src="{% static 'images/user.png' %}" height="14px" width="14px" id="user-icon" /><span id="user-name"> {{request.user.username}}</span></a> ... </body> -
Celery beat sends task regularly, but celery only processes them from time to time in production
I have a django project with celery integrated using redis. My celery worker works perfectly in local development, and now I'm deploying in production. Before daemonizing the process I want to see how celery behaves in the server. The thing is, celery beat sends the tasks correctly every minute (as I scheduled) but the worker seems not to receive it every time. Sometimes it requires 4/5 minutes until the task is received and processed. How is that possible? I have tried debugging, but there is very few information. see my setup: settings.py CELERY_TIMEZONE = 'Europe/Warsaw' CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' # Other Celery settings CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'predict_assistance.alerts.tasks.check_measures', 'schedule': crontab(minute='*/1'), }, } tasks.py from __future__ import absolute_import, unicode_literals from celery import shared_task @shared_task() def check_measures(): print('doing something') celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') app = Celery('predict_assistance') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() hereby my logs in production: [2020-03-11 16:09:00,028: INFO/Beat] Scheduler: Sending due task task-number-one (predict_assistance.alerts.tasks.check_measures) [2020-03-11 16:09:00,038: INFO/MainProcess] Received task: predict_assistance.alerts.tasks.check_measures[86f5c999-a53c-44dc-b568-00d924b5da9e] [2020-03-11 16:09:00,046: WARNING/ForkPoolWorker-3] doing something [2020-03-11 16:09:00,047: INFO/ForkPoolWorker-3] predict_assistance.alerts.tasks.check_measures[86f5c999-a53c-44dc-b568-00d924b5da9e]: doing something logger [2020-03-11 16:09:00,204: INFO/ForkPoolWorker-3] Task predict_assistance.alerts.tasks.check_measures[86f5c999-a53c-44dc-b568-00d924b5da9e] succeeded in 0.16194193065166473s: …