Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting an error : Reverse for 'college' not found. 'college' is not a valid view function or pattern name
urls.py: urls.py file contains : from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'), path('logout/', auth_views.LogoutView.as_view(), name="logout"), path('college/', views.CollegeView.as_view(), name="college"), path('signup/', views.SignUp.as_view(), name="signup"), ] views.py views.py file contains : from django.contrib.auth import login, logout from django.urls import reverse_lazy from django.views.generic import CreateView from . import forms from accounts.models import College # Create your views here. class CollegeView(CreateView): form_class = College fields = ['college'] success_url = reverse_lazy("login") template_name = "accounts/college.html" class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy("college") template_name = "accounts/signup.html" forms.py forms.py file contains : from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm from django import forms class UserCreateForm(UserCreationForm): class Meta: model = get_user_model() fields = ("username", "email", "password1", "password2") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["username"].label = "Display name" self.fields["email"].label = "Email address" class CollegeForm(forms.Form): fields = ("college") If i try to redirect the success url to login or logout then it works but for college it is not working -
Is npm in Node like virtualenv in Django?
I'm new to NodeJS and I'm having trouble understanding npm I'm following this tutorial and I can't seem to map the concepts tot he ones I know from my Django experience. Where exactly do my packages get installed? Can't I have project-specific packages like Django does with virtualenv? If I understand correctly this might cause compatibility issues in the future. -
Check words from a list as uppercase lowercase and mixed
i want to check if a user wants to use a forbidden username at sign up, sadly this currently only works with lowercase. How can i make this work for upper,lower,mixed scenarios? def forbidden_usernames(value): words = ["manager", "admin", "member", "staff", "support", "root"] if any(word in value for word in words): raise ValidationError( "Please don't use usernames like: admin, root, support etc.", code="invalid_username", ) -
assign multiple user to multiple events Django
So I'm trying to write a method which should enable the admin user who add users to assign them into events so that it becomes:users can have many events & events can have many users, and I want that to happen inside the event details, I couldn't figure it out Models.py class UserProfile(models.Model): user = models.OneToOneField(User, unique=True, on_delete=models.CASCADE,blank=True, null=True) # events = models.ManyToManyField(Event) entity = models.ForeignKey(Entity, default=1, on_delete=models.CASCADE,blank=True, null=True) phone_no = models.PositiveIntegerField(default=0,blank=True, null=True) name_en = models.CharField(max_length = 120 , default='',blank=True, null=True) job_name = models.CharField(max_length = 120, default='',blank=True, null=True) non_listed_entity = models.CharField(max_length = 120, default='', blank=True) first_time = models.BooleanField(default=True) def __str__(self): return self.user.username class TraineeInEvent(models.Model): trainees = models.ManyToManyField(UserProfile, blank=True, null=True, related_name="TraineeInOneEvent") def __str__(self): return '-'.join([str(trainee) for trainee in self.trainees.all()]) Views.py def event_detail(request, event_id): if request.user.is_staff: event = Event.objects.get(id=event_id) form = TraineeInEvent() if request.method == "POST": form = TraineeInEvent(request.POST) if form.is_valid(): form.save() context = { "event": event, "form":form, } else: return redirect('cal:no-access') return render(request, 'cal/detail.html', context) any Idea? -
Django templates don't get the context variables
We are using Django 2.1 for Speedy Net. I added an admin view for users - the URL of each user is the same URL of the user but with the prefix "/admin/user". I defined the admin user prefix with a context processor: def add_admin_user_prefix(request): if ((request.user.is_superuser) or (request.user.is_staff)): admin_user_prefix = "/admin/user" else: admin_user_prefix = "" return { 'admin_user_prefix': admin_user_prefix, } But the problem is, base templates and included templates don't see this variable. I don't use the only keyword when including templates. But still, base templates and included templates don't print anything when I print {{ admin_user_prefix }}. The prefix is to redirect the admin to the admin-specific user URL instead of the regular user URL. But I checked and the URLs are the regular URLs. In some cases the prefix is printed, and it seems to me that it's printed if it's not an included template and not a base template. What is the problem and How do I fix it? -
Y try to apply a modification on my template post list
y try to apply a modification on my template post list,y aplay aleady in post_list it's works but no in my template post_detail -
How to solve "value has an invalid date format" when Model.objects.bulk_create?
i have a data like this. listData = [{ .. 'termination_date': '2015-03-25 00:00:00', 'trainning_date': '1978-05-01 00:00:00', .. }] when i use " Model.objects.bulk_create" then show error below. django.core.exceptions.ValidationError: ['“2015-03-25 00:00:00” value has an invalid date format. It must be in YYYY-MM-DD format.'] this is my model termination_date = models.DateTimeField(blank=True, default='', null=True) trainning_date = models.DateTimeField(blank=True, default='', null=True) How simple way to solve this problem? -
Python - How to parse array of directories to string, and backwards
In my Django project I have array, that looks like that: [{'aa': '123', 'bb': '456','cc': '798'}, {'aa': '111', 'bb': '222','cc': '333'}, {'aa': 'a1', 'bb': 'b2','cc': 'c3'}] I want to write that array in the url (e.g. website.com/?data=[{aa...},{...}]), so then I can read that data parameter, and retrieve the array. I can't just write the array to the url (because of the special signs), so how can I parse the array to string, then unparse the string back to the original array (and be type 'array' - not string). -
Django navigator.sendbeacon csrf protection
I have a problem with navigator.sendBeacon('endpoint/', data). I have an error Forbidden (CSRF token missing or incorrect.) because it pass data via POST method. I know i should set csrf token, but I don't know how set it in this case, anyone have any idea how it should be done? I'm using Django==2.2.6. -
How to enable syntax highlighting for django template files in Atom Text Editor?
I am new to Django. Getting started with new syntax is easier if you have syntax highlighting. Any help is appretiated. -
How to store every search term to Database in Django
I have a search form on my website. When the user types a query (like iPhone) the program will store that keyword to a database called "SearchTerms" with the number of people who searched for that keyword. Example: search_term: iPhone search_count: 50 which means 50 peoples searched for the term "iPhone" on my website. I want the search term to be updated if the term exist, and added if the term does not exist. Here's what I tried to do: models.py class SearchTerms(models.Model): search_terms = models.CharField(max_length=255, blank=True, null=True) total_searches = models.IntegerField(default=0) updated_on = models.DateTimeField(auto_now_add=True) search_objects = SearchTermManager() class Meta: verbose_name_plural = "Search Terms" def __str__(self): return self.search_terms views.py class SearchView(ListView): template_name = 'search.html' paginate_by = 20 count = 0 def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['count'] = self.count or 0 context['query'] = self.request.GET.get('q') return context def get_queryset(self): request = self.request query = request.GET.get('q', None) if query is not None: product_results = Product.objects.search(query) # combine querysets queryset_chain = chain( product_results ) qs = sorted(queryset_chain, key=lambda instance: instance.pk, reverse=True) self.count = len(qs) # since qs is actually a list return qs return Product.objects.none() # just an empty queryset as default One more thing, is that I'm working with 2 tables. … -
AJAX call not working for sending tokens to API in Django
I have a token and need to pass it to an API in order to get back a time generated. I have used Simple-JWT for token generation but I am not able to send it to the URL specified. See my code below: models.py: class My_time(models.Model): id= models.ForeignKey(User, on_delete = models.CASCADE) entry_time = models.DateTimeField() views.py: #API to get back time (if existing) or create a new time and send it back to the HTML page via AJAX. class TimeAPI(generics.ListAPIView): permission_classes = [IsAuthenticated] serializer_class = MySerializer def get_queryset(self, request): current_time = timezone.now() if (My_time.objects.filter(time=current_time) in (None, '')): time = My_time.objects.create(time=current_time) #saves it to my database else: pass data = My_time.objects.values_list('time', flat=True) return data #should return the data to the HTML page urls.py: urlpatterns = [ # ..., path('time_api/',TimeAPI.as_view(), name = 'time_api'), ] interface.html: {% block content %} <form method="POST"> <button type="button" class="btn btn-outline-info" id ='get_time'> Punch In </button> <h4 id='display_time'></h4> </form> {% endblock content%} JS code (within the HTML page): {% block javascript %} <script type="text/javascript"> $('#get_time').click(function () { var access_token = localStorage.getItem('access'); #stored the token before in localStorage $.ajax({ cache: false, url: {% url 'time_api' %}, method: 'GET', // datatype: 'json', headers: { "Authorization": 'Bearer ' + access_token } success: … -
Page Can't Load with 'from skimage import io' in Apache
I have been trying to setup django + Apache on EC2. From the browser I can already successfully load the landing page using the django server. However once I switched to Apache, the page loads forever without any error message (because the page loading never stop). I have tried to narrow down the cause and found that the page can be successfully loaded if I exclude the line 'from skimage import io' from my code. Anyone has any clue on this and how to debug? Thanks! -
Django App Heroku Deployment: App not compatible with buildpack
Ive been through a lot of possible answers from here to everywhere, and it seems the problem persists. Please help. <3 $ git push heroku master Counting objects: 295, done. Delta compression using up to 4 threads. Compressing objects: 100% (272/272), done. Writing objects: 100% (295/295), 678.12 KiB | 8.07 MiB/s, done. Total 295 (delta 114), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to mydjangoappblog. remote: To https://git.heroku.com/mydjangoappblog.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/mydjangoappblog.git' Procfile gunicorn -
Why do you throw me as an invalid form when the values of the fields are correct in the POST?
I have the following code, that when I execute the form of localities it throws me that the form is not valid (for the rest it works well). If you can see, the form uses chained dropdowns) The fields that correspond to the model are loaded correctly. All the rest (which I obviously didn't put the code) works wonders OBS: Note that the keys are programmed and work correctly. I would appreciate if you can help me. Sorry my english. models.py: from django.db import models from django.contrib.auth import get_user_model class paises(models.Model): cpais = models.CharField(max_length=3, primary_key=True) pais = models.CharField('País',unique=True, max_length=30, blank = False, null = False) SINO = (('Si', 'Si'), ('No', 'No')) defecto = models.CharField(max_length=2, choices=SINO, default='No') vigente = models.CharField(max_length=2, choices=SINO, default='Si') fmodi = models.DateTimeField(auto_now=True) usumodi = models.CharField(max_length=30,blank = True, null = False) class Meta: verbose_name = 'País' verbose_name_plural = 'Países' ordering = ['pais'] def __str__(self): return self.pais class provincias(models.Model): cprovincia = models.CharField(max_length=3, primary_key=True) provincia = models.CharField(max_length=30, blank = False, null = False) cpais = models.ForeignKey(paises, on_delete = models.CASCADE,blank = True, null = True) SINO = (('Si', 'Si'), ('No', 'No')) defecto = models.CharField(max_length=2, choices=SINO, default='No') vigente = models.CharField(max_length=2, choices=SINO, default='No') fmodi = models.DateTimeField(auto_now=True) usumodi = models.CharField(max_length=30,blank = True, null = False) … -
Initialization script not executed when container is run in detached mode
I have a Dockerfile that builds a Django environment, which is based on an Ubuntu image and runs Apache HTTP Server. (httpd) Let's call that image backend_image. Along with another container for the PostgreSQL database, I plan to use this image as the development environment, firing both containers up and using the --network flag to connect them. I planned to have an initialization script within the backend_image, which creates the relevant tables whenever the backend container is run. The contents of the script is rather standard for a Django app, and are as follows. #!/bin/bash source ${VIRTUAL_ENV_DIR}/bin/activate python ${SCRIPT_LOCATION} makemigrations library python ${SCRIPT_LOCATION} migrate deactivate This script is run correctly when I run the backend_image in the foreground. (i.e. without the -d flag in the docker run command) I checked it by connecting to the database container using psql, and \dt command printed the relevant databases. However, in order to orchestrate the running of multiple containers required by the project, I need to run them in the detached mode. (I have a shell script running the containers, and connecting them) The problem is, when I run the backend container in detached mode, the tables are not created in the database … -
Page not found (404) in django url
This is my views.py def delete(request, id): employee = User.objects.get(id=id) employee.delete() return redirect('show') This is My urls.py url(r'^delete/<int:id>', core_views.delete), -
Python - Update a user with multiple type of users models in Django 2.2
I'm working on a project using Python(3.7) and Django(2.2) in which I have implemented models for multiple types of users by extending the base User model. Now I need to implement a way to allow the admin user to edit a user ( can't use the default Django admin). So, I have utilized the MultiModelForm to combine multiple forms on a single template, on the get request the form is loading properly with data populated. Here's what I have done so far: From models.py: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=255) title = models.CharField(max_length=255, choices=TITLE, blank=False) user_type = models.CharField(max_length=255, choices=USER_TYPE, blank=False) gender = models.CharField(max_length=255, choices=CHOICES, blank=False) contenst = models.CharField(max_length=255, blank=True, null=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) email_status = models.CharField(max_length=50, default='nc') USERNAME_FIELD = 'email' EMAIL_FIELD = 'email' REQUIRED_FIELDS = ['password'] objects = UserManager() def get_absolute_url(self): return "/users/%i/" % (self.pk) def __str__(self): return str(self.email) class ContactPerson(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) contact_email = models.EmailField(blank=False) customer_id = models.BigIntegerField(blank=True) contact_no = PhoneNumberField(blank=True, null=True, help_text='Phone number must be entered in the' 'format: \'+999999999\'. Up to 15 digits allowed.') collection_use_personal_data = models.BooleanField(blank=False) Here's the related forms.py: class EditUserForm(forms.ModelForm): password = None class Meta: … -
Why brower is not loading static files?
settings.py STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static_in_env') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static_root') MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') MEDIA_URL = '/media/' django.contrib.staticfiles' included in installed_apps. {% load static from staticfiles %} used in base.html. still getting these errors: [22/Dec/2019 13:45:31] "GET / HTTP/1.1" 200 10735 [22/Dec/2019 13:45:32] "GET /static/js/jquery-3.4.1.min.js HTTP/1.1" 404 1791 [22/Dec/2019 13:45:43] "GET /static/css/bootstrap.min.css HTTP/1.1" 404 1788 [22/Dec/2019 13:45:43] "GET /static/css/mdb.min.css HTTP/1.1" 404 1770 ...... -
"SecurityError: This operation is insecure" when calling domtoimage.toPng() in OpenLayers example
I am currently working on adding functionality to convert an OpenLayers Map into a png file (The example is here). However, when calling domtoimage.toPng() in the below code, Firefox (Ubuntu version 68.0.2) gives me the error SecurityError: This operation is insecure. I have checked all around and no one else seems to be having this problem with the dom-to-image library, and so I am stuck on how to fix this error. My JavaScript code for the Map is very similar to the code given in the example and is given here: <script type="text/javascript"> var extent = [0, 0, 3000, 4213]; var projection = new ol.proj.Projection({ code: 'my-image', units: 'pixels', extent: extent, }); var map = new ol.Map({ controls: ol.control.defaults().extend([ new ol.control.FullScreen() ]), layers: [ new ol.layer.Image({ source: new ol.source.ImageStatic({ attributions: 'My Image Attributions', url: "{{record | img_url}}", // Django stuff defined earlier projection: projection, imageExtent: extent }) }) ], target: 'map', view: new ol.View({ projection: projection, center: ol.extent.getCenter(extent), zoom: 2, maxZoom: 8 }) }); map.addOverlay(new ol.Overlay({ position: [0, 0], element: document.getElementById('null') })); // export options for dom-to-image. var exportOptions = { filter: function(element) { return element.className ? element.className.indexOf('ol-control') === -1 : true; } }; document.getElementById('export-png').addEventListener('click', function() { map.once('rendercomplete', function() { … -
Delpoying project django on heroku
hello every body please i need your help for solve my problem , this is the first time i delopied project django when i make push to my project and then i try to open it i find this massage enter image description here then when i write heroku login --t this mrssage enter image description here -
Why from django import * can't import all sub modules?
The asterisk (*) is used as a wildcard in from modue_name import *,it means import all sub modules in the module_name. ls /usr/local/lib/python3.5/dist-packages/django apps contrib dispatch __init__.py __pycache__ templatetags utils bin core forms __main__.py shortcuts.py test views conf db http middleware template urls The sub module apps located in django module. import django from django import * print(django.apps) Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'django' has no attribute 'apps' Why the sub module apps can't be imported by from django import *? -
How to convert word to pdf in django
I tried with comtypes but seem this library not support for ubuntu. So, anybody know library can work with ubuntu, please tell me. Thank you. -
Django: Help overwriting a model's save() method to auto populate a CharField based on a function on object creation
I have a model (Meal) with several many to many fields (proteins, carbohydrates and fats), which I recently added a 'name' CharField to. I wanted to allow the user to enter a name for a meal, but if they do not enter a name, I want the name to be populated automatically based on the function definitions I have in the model which just concatenate the names of the foods in one string. Now, if the Meal already exists, what I have actually works fine. However, if it does not exist, the food_name for each item appears not to have saved yet because they are empty. I put the super(Meal,self).save() statement before my if not self.name: statement in the hopes that this would save the object to the database so that the food_names could then be retrieved, but it does not work and instead when I do save the name is saved as '(0)'. What I am looking for the name to populate via the __str__ function as 'Pork Tenderloin, Spinach (steamed/boiled), Potato (Red, medium) (3)', for example. Also, if I don't call super(Meal,self).save() before the if statement, I actually get a 'maximum recursion depth exceeded' error. Can anyone tell … -
Intermediate model or manytomanyfield in django?
Currently i'm using a intermediate model for follow relationship in django as follows:- class FollowingProfiles(models.Model): Profile=models.ForeignKey(Profile,on_delete=models.CASCADE) ProfileName=models.CharField(max_length=120,blank=True,null=True) status=models.CharField(max_length=200,blank=True,null=True) def __str__(self): return self.ProfileName while the profile model as follows:- class Profile(models.Model): name=models.CharField(max_length=100,null=True,) Follwers=models.IntegerField(default='0') user=models.OneToOneField(User,on_delete=models.CASCADE,primary_key=True) bio=models.TextField(max_length=120,blank=True) location=models.CharField(max_length=30,blank=True) private=models.BooleanField(default=True) verified=models.BooleanField(default=False) ProfilePic=models.ImageField(upload_to='UserAvatar',blank=True,null=True) notif=models.BooleanField(default=False)#true when user have unread notification theme=models.CharField(max_length=100,default='normal') def __str__(self): return self.user.username should i use ManyToManyField or that intermediate model? is there any downside of any of these approaches?