Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
javascript file used in django is getting loaded with html content
html code: (my_django) [ my_lpar]# cat addlpar/templates/check.html <html><head><title>hello</title></head> <body> <div> <p> hey wassup </p> {% load staticfiles %} <script type="text/javascript" src="{% static 'js/check.js' %}"> </script> /div> </body> </html> js code: alert() When I start server, alert is not executed. So when I inspected the source of javascript file, from browser , check.js file is same as check.html: from browser: <html><head><title>hello</title></head> <body> <div> <p> hey wassup </p> <script type="text/javascript" src="/static/js/check.js"> </script> </div> </body> </html> And no obvious error is thrown in runserver: (my_django) [my_lpar]# python3.5 manage.py runserver <ip:port> Performing system checks... System check identified no issues (0 silenced). April 28, 2020 - 17:35:07 Django version 2.1, using settings 'my_lpar.settings' Starting development server at <ip:port> Quit the server with CONTROL-C. [28/Apr/2020 17:35:10] "GET /static/js/check.js HTTP/1.1" 200 168 [28/Apr/2020 17:35:11] "GET /static/js/check.js HTTP/1.1" 200 168 [28/Apr/2020 17:35:11] "GET /favicon.ico HTTP/1.1" 200 168 Please somebody help me to solve this weird issue. Why Am I not able to see javascript content.?? -
Django MySql Fulltext search works but not on tests
I used this SO question to enable full text search on a mysql db in Django application. # models.py class CaseSnapshot(BaseModel): text = models.TextField(blank=True) class Search(models.Lookup): lookup_name = "search" def as_mysql(self, compiler, connection): lhs, lhs_params = self.process_lhs(compiler, connection) rhs, rhs_params = self.process_rhs(compiler, connection) params = lhs_params + rhs_params return f"MATCH (%s) AGAINST (%s IN BOOLEAN MODE)" % (lhs, rhs), params models.TextField.register_lookup(Search) Because Django does not support full text search on mysql, we have to add our index, so we modify the generated migration file: # Generated by Django 2.2 on 2020-04-28 03:41 from django.db import migrations, models # Table details table_name = "by_api_casesnapshot" field_name = "text" index_name = f"{table_name}_{field_name}_index" class Migration(migrations.Migration): dependencies = [("by_api", "0033_add_tag_color")] operations = [ migrations.CreateModel(...), # As auto-generated migrations.RunSQL( f"CREATE FULLTEXT INDEX {index_name} ON {table_name} ({field_name})", f"DROP INDEX {index_name} ON {table_name}", ), ] Checking the Work # dbshell mysql> SHOW INDEX FROM by_api_casesnapshot; +---------------------+--------------------------------+-------------+-----+------------+-----+ | Table | Key_name | Column_name | ... | Index_type | ... | +---------------------+--------------------------------+-------------+-----+------------+-----+ | by_api_casesnapshot | PRIMARY | id | ... | BTREE | ... | | by_api_casesnapshot | by_api_casesnapshot_text_index | text | ... | FULLTEXT | ... | +---------------------+--------------------------------+-------------+-----+------------+-----+ #shell >>> snap = CaseSnapshot.objects.create(text="XXX") # Regular query first >>> CaseSnapshot.objects.filter(text__contains="X") … -
Django Query - How to filter object to exclude a single item?
I am trying to create a blog project in which i want to show other blogs link in right side apart from the blog which i am on currently? I have tried it But i am getting an error. Here is Code def redirect(request, slug): try: exists = Blog.objects.get(title=slug) except Blog.DoesNotExist: raise Http404("Page Not Found") context = { 'content': exists, 'otherBlogs': Blog.objects.all().exclude(exists) } return render(request, "blog.html", context) I want to exclude exists from otherBlogs How can i do that? Thanks in Advance... -
Django:where should i put the admin page of my website?
Actually I'm working on a Django project.we all know to access an admin panel of the site we have the URL to access it. like this. path('admin/', admin.site.urls), Anyone can access this URL and try to attempt a log-in admin panel but I want that only super-user can access this page no anyone. How to do this. If Users of my site try to access this page does this is safe or not for my site. -
how to access Moodle REST webservice in django python
I have created a webservice which allows me to create users. But i donot know how to access it in django and how to use it. I tried following this link pypi.org/project/moodle-ws-client but it didn't get me anywhere. -
Use email created on cpanel in django
I have created an email id on my cpanel, I want to use it in django. As for gmail we write, EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_USE_SSL = False EMAIL_PORT = 587 EMAIL_HOST_USER = 'email@gmail.com' EMAIL_HOST_PASSWORD = 'password' What should we write for the id that has been created using cpanel. I have no idea regarding this as I am a begineer. -
Using Django SessionStore in Celery
I'm really struggling with something and have tried for days to find out what I'm doing wrong..I was thinking there might be something fundamentally wrong with what I am trying to do but I cant find anything to suggest that. I am trying to use Celery to modify a Django Session DB in the background. As a test, I have a test view which passes the sessionid to this celery task: @shared_task(name="test_celery_task") def test_celery_task(sessionid): s = SessionStore(session_key='sessionid') s['test_var'] = ["Success"] s.save() return "Task Complete" I can see the task runs, and I have added a few loggers in to check the session ID gets passed, and no error are thrown up etc. When I do this in the manage.py shell, it works fine. But I guess this is not working because it is being run by a celery worker. If it is not possible, then so be it and I'll save my time trying to work out what's wrong, but all I have read suggests that I should be able to manipulate models etc within Celery without an issue, and that a session is just another model. Am I going about this all wrong? Does anyone have any experience with … -
Save images from Form to database using ImageField Django
I am trying to save images from my Form to my database in django. All of my other CharFields seem to save from my form but not the images. When I go to admin I can upload and save images to a specified media folder and it works however, the images dont seem to save. Please help very confused, also new to this so my code may be a mess, much help is needed. Thanks [views][1] [model][2] [form][3] [urls][4] [settings][5] [1]: https://i.stack.imgur.com/ttiOz.png [2]: https://i.stack.imgur.com/EcDQQ.png [3]: https://i.stack.imgur.com/WF3YG.png [4]: https://i.stack.imgur.com/QGRzW.png [5]: https://i.stack.imgur.com/zmRxh.png -
Parent and children pagination in django
in django i have category model and post model each category has got a lot of posts so now i wanna render the tag with all its post and make pagination in there /web_dev Ex of tag name and when it takes me there i want to view all the specific tag posts and the posts might be a lot so how to add pagination using whatever weather TagDetailView(): or anything Code here : class TagDetailView(DetailView, MultipleObjectMixin): model = Tags template_name = 'one_tag.html' paginate_by = 3 def get_context_data(self, **kwargs): object_list = Posts.objects.filter(tag_belongs=self.get_object()).order_by('-id') context = super(TagDetailView, self).get_context_data(object_list=object_list, **kwargs) return context So in each tag to be viewed i wanna all its posts but with pagination feature -
IP error: fjango app not deploying with docker
I am new to Docker so I'm probably missing something obvious but here goes. I am trying to test a simple Django app with docker postgres. All I want right now is to verify that the home page is working on localhost. Debug output window gives me the following: web_1 | System check identified no issues (0 silenced). web_1 | April 28, 2020 - 17:06:23 web_1 | Django version 3.0.5, using settings 'app.settings' web_1 | Starting development server at http://0.0.0.0:8000/ web_1 | Quit the server with CONTROL-C. However when I go to 0.0.0.0:8000 I get an error that says the site can't be reached "The webpage at http://0.0.0.0:8000/ might be temporarily down or it may have moved permanently to a new web address. ERR_ADDRESS_INVALID Here is my docker-compose.yml: version: '3.7' services: web: build: . command: python /app/manage.py runserver 0.0.0.0:8000 volumes: - .:/app ports: - 8000:8000 depends_on: - db db: image: "postgres:latest" ports: - "5432:5432" environment: - "POSTGRES_HOST_AUTH_METHOD=trust" Here is my dockerfile: # Pull base image FROM python:3.8 # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # Set work directory WORKDIR /app # Install dependencies COPY requirements.txt requirements.txt RUN pip install -r requirements.txt # Copy project COPY . /app/ … -
unsupported operand type(s) for -: 'str' and 'datetime.datetime' - from models
I get an error in my models.py file. class TimeAnswerElement(models.Model): email = models.EmailField() costumer_time = models.DateTimeField() my_time = models.DateTimeField(auto_now_add=True) time_compartment = models.DateTimeField(blank=True, null=True) #helped function def save(self, *args, **kwargs): super().save(*args, **kwargs) TimeAnswerElement.objects.filter(pk=self.pk).update(time_compartment=self.field_compartment_function()) def field_compartment_function(self): time = self.costumer_time - self.my_time return time I am trying to subtract two fields that are correctly saved in the model through my view. Why raises my error. in my object where I use properties to override time_compartment, I don't have a string. I have correctly saved date. My views.py if request.method == 'POST' and 'save' in request.POST: form = NewTimeForm(request.POST) if form.is_valid(): cd = form.cleaned_data object = form.save(commit=False) my_date = '%s %s' %(date, cd['time']) object.costumer_time = my_date object.save() else: form = NewTimeForm() How to subtract two dates correctly by property. Do I have to use something like this for my fields? s = "2014-04-07" datetime.datetime.strptime(s, "%Y-%m-%d").date() Or is there a better way to solve this? -
Django: issue with loading static in deployment
I know this question has similar ones but nothing has been able make it for me. My static files are not loading although I feel like have followed the procedure well. I am hoping that a pair a fresh eye could spot the detail that I am missing urls.py .... if settings.DEBUG: setting.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) public_urls.py .... if settings.DEBUG: setting.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) settings.py STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'collected_static') MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') STATICFILES_DIRS = [os.path.join(BASE_DIR, "staticfiles"), ] and then what is in /etc/nginx/sites-enabled/django.conf server { listen 80; server_name 35.180.131.203; location / { include proxy_params; proxy_pass http://unix:/home/ubuntu/exostocksaas/app.sock; } location /staticfiles/ { autoindex on; root /home/ubuntu/exostocksaas/inventory4/staticfiles/; } } and my errors are that the static files are not loading: GET http://35.180.131.203/css/sb-admin-2.min.css net::ERR_ABORTED 404 (Not Found) and the same for all the statics Am I missing something obvious here, I am out of things to try and any help would be welcome -
How pass a td value from html template to my views.py
Am fairly new to django, so trying to play around with django and learn at the same time by building a small project. Basically I have the below code in my html template: <tbody> {% for items in queries %} <tr> <td>{{ items.ana_user }}</td> <td class="text-center">{{ items.ana_public }}</t> <td>{{ items.ana_private }}</td> <td class="text-center">{{ items.ana_bytestx }} MB</t> <td>{{ items.ana_bytesrx }} MB</td> <td class="text-center">{{ items.ana_policy }}</t> <td>{{ items.ana_duration }}</td> <td class="btn-group"> <button class="btn btn-secondary btn-sm dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Options </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="{% url 'stats' %}">View Live Graph</a> <a class="dropdown-item" href="{% url 'disconnect' %}">Disconnect Users</a> </div> </td> </tr> {% endfor %} </tbody> Basically by clicking any of the dropdown action. I want to take the value of the first td which is 'items.ana_user' and pass this to my views.py as a 'request.POST.get'. Your help is very much appreciated as usual. -
Can you trigger a signal upon partial update of django object via the django rest framework?
I started noticing that the patch method in django rest framework doesn't actually trigger signals, post methods seem to work fine. This is what I have: @receiver(signals.pre_save, sender=Example) def populate_time_fields_based_on_state(sender, **kwargs): example = kwargs.get('instance') if example.start_datetime is None and example.projected_end_datetime is None and example.state.label == 'Assigned': example.start_datetime = datetime.datetime.now() example.projected_end_datetime = example.created_datetime + datetime.timedelta( days=example.som_field) example.save() And I'm testing this via: client = APIClient() client.patch(f'/api/example/1/', {'state': 'Assigned'}) Is there a way to tell it to trigger the signal? Do I need to override the update method in my serializer? -
Function has no objects member pylint
I am using django 3 i am getting Function product has no object member error in this objects.all() method in my views.py file can anyone help please from django.db import models from django.shortcuts import render from django.http import HttpResponse # Create your views here. from .models import models def pro(request): pro = **product**.objects.all() return render(request , 'accounts/pro.html' , {'product' : pro}) MODELS.PY class product(models.Model): CATEGORY= ( ('InDoor' , 'InDoor'), ('OutDoor' , 'OutDoor'), ) name= models.CharField(max_length = 245 , null=True) price= models.FloatField(null = True) category= models.CharField(max_length=245 , null=True , choices = CATEGORY) description=models.CharField(max_length=500 , null= True , blank=True) date_created=models.DateTimeField(auto_now_add=True , null = True ) tags=models.ManyToManyField(tag) def __str__(self): return self.name -
Django restricting access
How do I restrict user from going on logout page. For example in my project I have a logout page with url logout/. So if a type /logout/ in my address bar it takes me to that page which is meaningless. So how do I make it so only when user click on logout button then only it shows that logout page.(my login-logout system works fine just that I am not able to restrict users from accessing that logout page simply by typing logout/) -
Uncaught TypeError: Cannot read property 'ajax' of undefined in GeoJson Leaflet
I am using ajax query for geoJson data. However, I am not able to load the data into the leaflet maps. Using a sample ajax query such as this, when I look in the console I am able to find the data. Not sure what I am doing wrong. Any help will be greatly appreciated :) Thanks. [ $.ajax({ type: 'GET', url: 'location', //data: { get_param: 'value' }, dataType: 'json', success: function (data, status) { console.log(data); geojson = data } }); function our_layers(map,options){ var Location = L.geojson.ajax("{% url 'location' %}",{ }); }; ]1 -
Ajax call to populate form fields django from with a click button return
I would like to fill my django field form the return of the click button function. The reason of doing that is to allow both manual and the click button options. the click button function collects readings from a serially connected device. how can I use the ajax call for this purpose - appreciate your help. a screen shot of my page enter image description here -
Get Images from Request in Django
I have the following data in request.data <QueryDict: {'eventID': ['1'], 'image_0': [<InMemoryUploadedFile: Bohr.jpg (image/jpeg)>], 'image_1': [<InMemoryUploadedFile: ptcl.png (image/png)>], 'image_2': [<InMemoryUploadedFile: PTCL.jpg (image/jpeg)>], 'image_3': [<InMemoryUploadedFile: ptcll.png (image/png)>]}> This is my code which I am using to get the values but it works only there is only one value of an image. def AddGallery(request): status={'ErrorCode':-1,'ErrorMsg':'Initial-request Add images'} context = {} try: print (request.data) event = request.data.get('eventID', None) image = request.data.get('image', None) usr_mgmt =UserAuthenticationA() status = usr_mgmt.AddGallery(event, image) except Exception as e: print (str(e)) context.update(status) return Response(context) I need the solution with which I can extract the multiple images. Thanks in Advance!!!! -
Dynamic DOM update breaks Django Endless Pagination
I'm using Django EL(Endless) Pagination to emplement a lazy-loading Twitter style pagination on my website. Everything works well. But I'd like my users to be able to dynamically delete some of the paginated results on a button click. So I added this ajax call: $("main").on("click", ".close", function() { let id = $(this).attr("id"); $.ajax({ url: urltomydeleteview, timeout: 0, method: 'POST', }) .done((res) => { $(this).closest('div.col-sm-12').remove(); ... other DOM manipulations .... }) }); That creates a bug, of course: if a user delete several elements and reaches the bottom of the page, the lazy pagination is called with wrong parameters and I got a 404. How can I tell Django EL that my queryset has changed without reloading my page? -
How safe it is to pass a model-object ID as a parameter in a request?
I'm new to web development, so here's the situation: I have a model named Qualifier, that has a name and several other fields. It has a reference to 1 and only 1 User, but doesn't have any other unique fields. e.g.: class Qualifier(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=32) other_field = models.IntegerField(default=0) I also have a view that loads, in a list, all Qualifier objects that belong to the accessing User: they are fetched by the fields user since there's no other "unique field" to distinguish. def qualifiers_view(request): # Access Restriction if not request.user.is_authenticated: return redirect("accounts:login") # Fetch company users qualifiers = Qualifier.objects.filter( user=request.user ) return render(request, 'qualifiers.html', {'qualifiers': qualifiers}) But here's a problem: In the view template, within each row of this list, beside each Qualifier, there's a DELETE button (a "POST" form) intended to call a view that deletes that same Qualifier, based on the parameter(s) passed... but it seems inefficient to me to pass user and name as the parameters, because it would result in another search through the database to find it. I thought: An other option would be to get the Qualifier object's ID's in the DB upon the first search (when the list … -
Should I use StreamingHttpResponse or should I simply send multiple requests to the server?
I am working on a Django project and I need some help deciding which paradigm to use. I don't know how Django behaves in a production since this is the first project that I am intending to release. I am currently using StreamingHttpResponse in Django alongside JavaScript Fetch and ReadableStream APIs to send data from the server to the client over a long period of time. How the app works is that the server is responsible for repeatedly running a simulation (separate to Django), which reports its progress to my Django app. When a client connects , the client sends a request to Django for the progress info and while the simulation is running , Django opens a stream (StreamingHttpResponse) and periodically sends that progress information of the simulation back to the client-- which then shows a progress bar in the browser. The simulation can take hours to complete. I am inexperienced , so the way I tested this (using the development server mind you ) , is to simply open a ton of tabs and point them to the app. Django only allows six of those tabs to connect at a time and only when the stream closes for … -
What can I do to make this function work?
I wrote this login function with a recaptcha but it doesn't work. def LogIn(request): if request.user.is_authenticated: return redirect('home') elif request.method == 'POST': form = AuthenticationForm(request.POST) if form.is_valid(): recaptcha_response = request.POST.get('g-recaptcha-response') url = 'https://www.google.com/recaptcha/api/siteverify' values = {'secret': settings.RECAPTCHA_SECRET_KEY,'response': recaptcha_response} data = urllib.parse.urlencode(values).encode() req = urllib.request.Request(url, data=data) response = urllib.request.urlopen(req) result = json.loads(response.read().decode()) username = request.POST['username'] password = request.POST['password'] if (result['success']) and (result['action'] == 'login'): messages.success(request, "Welcome") user = authenticate(request, username=username, password=password) login(request, user) return redirect('home') else: messages.error(request, 'Invalid reCAPTCHA. Please try again.') else: form = AuthenticationForm return render(request, 'login.html', {'form': form}) the recaptcha works, I tried it with the signup function and it works so it's not the recaptcha. when I try to login and press the submit button it just refreshes the page. what am I doing wrong here? and if there's some mistakes in my code or something I could learn please tell me I will really appreciate it. thanks -
i can't get the background image .please solve the issue
here are some files from project hope so they help you to fix this error. my setting.py """ Django settings for advice_lancing project. Generated by 'django-admin startproject' using Django 3.0.5. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '(71f#n^0en3u1=j=%bthg1m%d2=so=3+@p6=2u+5k)04caf+od' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'markdownx', 'blog', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'advice_lancing.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR,], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'advice_lancing.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', … -
m2m relationship in PostgreSQL
I have two models related through a third: class Order(models.Model): parts = models.ManyToManyField(Part, through='invent.UsedPart') class Part(models.Model): class UsedPart(models.Model): part = models.ForeignKey(Part, on_delete=models.CASCADE) order = models.ForeignKey('mtn.Order', on_delete=models.CASCADE) This schema worked ok in SQLite, but when i tried to migrate it to PostgreSQL i get this error: Running migrations: Applying invent.0002_auto_20200428_1105...Traceback (most recent call last): File "/home/vadim/.local/lib/python3.6/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) psycopg2.errors.DuplicateColumn: column "order_id" of relation "invent_usedpart" already exists Did I define them wrong way?