Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Visual studio code python/django debbuger cannot find GDAL lib
Although I can debug my project from the terminal, when I am trying to debug from visual studio code i get this error: File "/home/chris/.virtualenvs/floodsam/lib/python3.5/site-packages/django/contrib/gis/gdal/libgdal.py", line 43, in <module> % '", "'.join(lib_names) django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal2.2.0", "gdal2.1.0", "gdal2.0.0", "gdal1.11.0", "gdal1.10.0", "gdal1.9.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings. sh-4.3$ This is my launch.json { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "pythonPath": "${config:python.pythonPath}", "args": [ "runserver", "--noreload", "--nothreading" ], "debugOptions": [ "RedirectOutput", "Django" ] }, These are my visual studio code project settings: { "python.venvPath": "~/.virtualenvs", "python.pythonPath": "~/.virtualenvs/floodsam/bin/python3", "workbench.colorTheme": "Monokai", "python.autoComplete.addBrackets": true, "editor.minimap.enabled": true, "python.venvFolders": [ "envs", ".pyenv", ".virtualenvs", ".direnv" ] } As I said project runs from command line: (floodsam) chris@chris-Lenovo ~/D/w/floodsam> ./manage.py runserver Performing system checks... System check identified no issues (0 silenced). June 10, 2018 - 06:43:32 Django version 2.0.6, using settings 'floodsam.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. What am I doing wrong? -
Make two foreignkey unique on same model
I have a model like this: class Connection(models.Model): start = models.ForeignKey( 'Point', on_delete=models.PROTECT, related_name='start_point', ) end = models.ForeignKey( 'Point', on_delete=models.PROTECT, related_name='end_point', ) length = models.DecimalField( max_digits=3, decimal_places=1, ) What's the best way to make sure 'start' and 'end' points are not the same? Is there anything like UNIQUE_INDEX(start,end) in MySQL? Or there's only the form validation method? -
Using django-oscar search facets using solr
I am having difficulty implementing django-oscar search facets. I was able to use SimpleProductSearchHandler class but I have trouble finding out how SolrProductSearchHandler works and where it renders the search facets on the page. If anyone has used solr to implement search facets, please guide me on this one. -
ManyToMany Fields do not get filled or throws TypeError when creating an entity
This is a problem which I've been fighting with for a while and now I gave up. I am writing a User/Profile model in Django 2.0.2 (python 3.6 + postgres 10 on Linux) which is as follows : class Config_Table(models.Model): entity_name = models.TextField(primary_key=True) category = models.TextField() description = models.TextField(blank=True,default='') Above table keeps some static information which gets me into trouble. class UserProfile(AbstractUser): "The Profile of a user with details are stored in this model." username = models.TextField(primary_key=True, max_length=11) first_name = models.TextField(max_length=50,blank=True,default='') last_name = models.TextField(max_length=100,blank=True,default='') phone_number = models.TextField(max_length=11,blank=True,default='') avatar = models.ImageField(blank=True, upload_to='Pictures/') GENDER_CHOICES = ( ('M','Male'), ('F','Female'), ) gender = models.CharField(max_length=1,choices=GENDER_CHOICES, default='M') city = models.TextField(max_length=25, blank=True, default='NY') description = models.TextField(max_length=2000, blank=True, default='') interests = models.ManyToManyField(Config_Table, blank=True, default='') date_of_birth = models.DateField(blank=True) official_docs = models.ImageField(blank=True, upload_to='Pictures/') team_name = models.TextField(blank=True,default='') debit_card_number = models.IntegerField(blank=True, default=0) MUSIC_CHOICES = ( ('Rock','Rock Music'), ('Trad','Traditional Music'), ('Elec','Electronic Music'), ('Clas','Classical Music') ) favorite_music = ArrayField(models.TextField(blank=True,default=''),size=2,blank=True, default='{}') class Meta: permissions=(("User","User level permission"), ("Tour","Tourleader level permission"), ("Admin","Administrators")) my views.py : class UserList(APIView): """ List all users, or create a new user. """ def get(self, request, format=None): users = UserProfile.objects.all() target_users = [] for user in users.iterator(): if user.is_superuser == False: target_users.append(user) serializer = UserProfileSerializer(target_users, many=True) return Response(serializer.data) def post(self, request, format=None): serializer … -
Applying custom mixin and lookups with Q objects behavior
I have the following mixin in which I want retrieve the User model data to place these data on different clase based views that I am developing: class UserProfileDataMixin(object): def get_context_data(self, **kwargs): context = super(UserProfileDataMixin, self).get_context_data(**kwargs) user = self.request.user #context['userprofile'] = user.profile if user.is_authenticated(): context['userprofile'] = user.profile return context Then, I have the following search view in which I have lookup users according to the following criteria with Q objects: When we search by username and full_name field class SearchView(UserProfileDataMixin, ListView): template_name = 'search.html' def get(self, request, *args, **kwargs): query = request.GET.get("q") qs = None if query: qs = User.objects.filter( Q(username__icontains=query) | Q(full_name__icontains=query) ) context = {"users": qs} return render(request, "search.html", context) When I inherit from UserProfileDataMixin this mixin gives me the possibility of having the userprofile context variable to pass it to my search.html template, which inherit from layout.html template, in which I perform the following validation: search.html template {% extends "layout.html" %} layout.html template {% if userprofile %} I put the data of user by example: avatar, username, full_name, and menu options to my app. {% endif %} Until here, alls OK, but my class based view SearchView does not apply the UserProfileDataMixin because, I cannot get the … -
How can i find the file /app/.heroku/python/.../password_reset_email.html?
when I run my application locally, the rest password works and everything perfectly fine. and once I run the app on Heroku, it shows this error and I couldn't figure out how to find this template. i would appreciate if someone helps me solve this issue. Traceback: File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/views.py" in inner 54. return func(*args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/views.py" in password_reset 306. form.save(**opts) File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/forms.py" in save 289. email, html_email_template_name=html_email_template_name, File "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/auth/forms.py" in send_mail 236. body = loader.render_to_string(email_template_name, context) File "/app/.heroku/python/lib/python2.7/site-packages/django/template/loader.py" in render_to_string 68. return template.render(context, request) File "/app/.heroku/python/lib/python2.7/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context) File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py" in render 207. return self._render(context) File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py" in _render 199. return self.nodelist.render(context) File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context) File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py" in render_annotated 957. return self.render(context) File "/app/.heroku/python/lib/python2.7/site-packages/django/template/defaulttags.py" in render 40. output = self.nodelist.render(context) File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context) File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py" in render_annotated 957. return self.render(context) File "/app/.heroku/python/lib/python2.7/site-packages/django/template/loader_tags.py" in render 63. result = self.nodelist.render(context) File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context) File "/app/.heroku/python/lib/python2.7/site-packages/django/template/base.py" in … -
Python multiprcessing with Django Queryset works well but it stops at the end:
I run multiprocessing tasks with django Queryset in django command Here is my code: df = pd.read_csv("my_stock_data.csv") def run(p): v = p.volume code = p.symbol.code date = p.date global df num_cols = 5 index = df.columns.get_loc('A' + code) _df = df[df.columns[index:index+num_cols]].dropna(how='all') _df.columns = ['open', 'high', 'low', 'close', 'volume'] try: _p = _df.loc[date] except Exception as e: print(p.symbol, e) return if v != _p['volume']: print(p.symbol, v, _p['volume']) return class Command(BaseCommand): def handle(self, *args, **options): qs = DailyPrice.objects.all() pool = Pool(12) pool.map(run, qs) pool.close() pool.join() As you can see here pool map the funtion with queryset. Problem is that it works and run perfect except when it reached to the end of queryset, it stopped, which means the program didn't finished. I think that the problem is due to the fact that I passed queryset, not list or something. So I tried like below: df = pd.read_csv( os.path.join(settings.PROJECT_ROOT_DIR, "data_0525", "stock_all.csv"), index_col=0, parse_dates=True, ) def run(p): v = p[0] code = p[1] date = p[2] global df num_cols = 5 index = df.columns.get_loc('A' + code) _df = df[df.columns[index:index+num_cols]].dropna(how='all') _df.columns = ['open', 'high', 'low', 'close', 'volume'] try: _p = _df.loc[date] except Exception as e: print(code, e) return if v != _p['volume']: print(code, v, _p['volume']) … -
CSRF cookie not set in Django admin panel
I'm a newbie in django and actually using Nginx + Gunicorn running in Ubuntu Server. And well, I'm getting this error. When I try to login into my Django automatic generated Admin Dashboard https://example.com/admin, appears: Forbidden (403) CSRF verification failed. Request aborted. In my console log it appears: Forbidden (CSRF cookie not set.): /admin/login/ Since I've added https with CloudFlare, I've added additional domains into my settings, here is where my problem begins: Django settings for example project. Generated by 'django-admin startproject' using Django 2.0. For more information on this file, see https://docs.djangoproject.com/en/2.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.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__))) MEDIA_URL = '/descargas/' GOOGLE_RECAPTCHA_SECRET_KEY = '' CSRF_TRUSTED_ORIGINS = ['.example.com'] CSRF_COOKIE_DOMAIN = ['.example.com'] CSRF_COOKIE_SECURE = True #I've already tried change this to False #Max file size MAX_UPLOAD_SIZE = "5242880" # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1', 'example.com', 'www.example.com', 'Server IP'] #GOOGLE DRIVE KEY GOOGLE_DRIVE_STORAGE_JSON_KEY_FILE = '' … -
Flat JSON to Nested JSON using Django RestFramework
I've got a json in my view as below, { "name":"myname", "age":30, "day":20, "month":"June", "year":1988 } How can I convert it to a nested JSON as below using Serializers?, { "name":"myname", "age":30, "DOB":{ "day":20, "month":"June", "year":1988 } } -
Django cant get registration form to post to database in admin.py
Hi I am trying to get my ModelForm to post to my database so I can see if users are actually registered in my database. The actual database shows up in admin.py but when I enter the information in my Django made ModelForm it will not POST to the database therefore will not see anything listed under my ModelForm in admin.py, could you please help me? VIEWS.PY from django.shortcuts import render from App1 import forms from App1.forms import LogInForm, SignedUpForm from django.contrib.auth import authenticate, login, logout from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required from django.template import RequestContext # Create your views here. def index(request): form = LogInForm() if request.method == 'POST': emailview = request.POST.get('email') passwordview = request.POST.get('password') varauth = authenticate(username=emailview, password=passwordview) if varauth: if varauth.is_active: login(request, varauth) request.varauth return HttpResponseRedirect(reverse('index')) else: return HttpResponse("Account Not Active") else: print("Someone tried to log in and failed") print('Username: {}\nPassword: {} '.format(emailview, passwordview)) return render(request, 'App1/index.html', {'form': form}) @login_required def special(request): return HttpResponse("YOU ARE LOGGED IN") @login_required def activeuserlogout(request): logout(request) return HttpResponseRedirect(reverse('index')) def terms_and_conditions(request): return render(request, 'App1/termsandconditions.html') # LAST EDITED CHANGE IN THE POST GET PARAMETER def Registernow(request): form2 = SignedUpForm() if request.method == 'POST': form2 = SignedUpForm(request.POST) if … -
Django - Value error when adding app name in 'INSTALLED APPS'
When i add my app name in INSTALLED APPS inside settings.py file, i got the following error and its removed when i erase my app name from settings. What is the problem here? Unhandled exception in thread started by <function check_errors. <locals>.wrapper at 0x0000007BFA7BB598> Traceback (most recent call last): File "C:\Users\postgres\AppData\Local\Programs\Python\Python36\lib\site- packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\postgres\AppData\Local\Programs\Python\Python36\lib\site- packages\django\core\management\commands\runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "C:\Users\postgres\AppData\Local\Programs\Python\Python36\lib\site- packages\django\utils\autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "C:\Users\postgres\AppData\Local\Programs\Python\Python36\lib\site- packages\django\utils\six.py", line 685, in reraise raise value.with_traceback(tb) File "C:\Users\postgres\AppData\Local\Programs\Python\Python36\lib\site- packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Users\postgres\AppData\Local\Programs\Python\Python36\lib\site- packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\postgres\AppData\Local\Programs\Python\Python36\lib\site- packages\django\apps\registry.py", line 108, in populate app_config.import_models() File "C:\Users\postgres\AppData\Local\Programs\Python\Python36\lib\site- packages\django\apps\config.py", line 202, in import_models self.models_module = import_module(models_module_name) return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 674, in exec_module File "<frozen importlib._bootstrap_external>", line 781, in get_code File "<frozen importlib._bootstrap_external>", line 741, in source_to_code File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed ValueError: source code string cannot contain null bytes -
Django - UpdateView ModelForm setting initial value on queryset field
I'm trying to update a model object where one of the values is derived from a queryset. The object creation works perfectly - it uses a queryset that is passed to the template and then on the POST it is saved into the object. My Question: The field named parent_jury is showing up in the template as an empty choicefield. It doesn't contain the original field value. How do I get it to set the initial field value to what is in the object and allow the user to select from other values in the queryset? But now I'm trying to update the object. Here's the code: #forms.py def __init__(self, *args, **kwargs): pk = kwargs.pop('pk') yr = kwargs.pop('yr') jr = kwargs.pop('jr') self.customer_id = pk self.court_year_id = yr super().__init__(*args, **kwargs) # This prints the correct value for the the object I'm trying to update print("pr: ", Jury.objects.get( jury_id=jr).parent_jury) # This is my latest attempt to get the initial value (or any value) to # be presented in the modelform/template. self.fields['parent_jury'].initial = Jury.objects.get( jury_id=jr).parent_jury Besides the code above, I've also tried to pull the right __init__() values using this: #forms.py (other attempts) self.fields['parent_jury'] = forms.ChoiceField( required = False, choices = Jury.objects.filter( customer_id=pk).filter( … -
Static file Error when push django app to heroku - python3 vs python
I set the remote, initialized git than added the files. When I go to push the following error occurs: git push heroku master Counting objects: 59, done. Delta compression using up to 8 threads. Compressing objects: 100% (53/53), done. Writing objects: 100% (59/59), 19.10 KiB | 0 bytes/s, done. Total 59 (delta 8), reused 0 (delta 0) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: ! The latest version of Python 3 is python-3.6.5 (you are using python-3.5.2, which is unsupported). remote: ! We recommend upgrading by specifying the latest version (python-3.6.5). remote: Learn More: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.5.2 remote: -----> Installing pip remote: -----> Installing requirements with pip remote: Collecting Django==2.0.4 (from -r /tmp/build_aa69fb831acf322358f0bb817d4a520e/requirements.txt (line 1)) remote: Downloading https://files.pythonhosted.org/packages/89/f9/94c20658f0cdecc2b6607811e2c0bb042408a51f589e5ad0cb0eac3236a1/Django-2.0.4-py3-none-any.whl (7.1MB) remote: Collecting gunicorn==19.8.1 (from -r /tmp/build_aa69fb831acf322358f0bb817d4a520e/requirements.txt (line 2)) remote: Downloading https://files.pythonhosted.org/packages/55/cb/09fe80bddf30be86abfc06ccb1154f97d6c64bb87111de066a5fc9ccb937/gunicorn-19.8.1-py2.py3-none-any.whl (112kB) remote: Collecting pytz (from Django==2.0.4->-r /tmp/build_aa69fb831acf322358f0bb817d4a520e/requirements.txt (line 1)) remote: Downloading https://files.pythonhosted.org/packages/dc/83/15f7833b70d3e067ca91467ca245bae0f6fe56ddc7451aa0dc5606b120f2/pytz-2018.4-py2.py3-none-any.whl (510kB) remote: Installing collected packages: pytz, Django, gunicorn remote: Successfully installed Django-2.0.4 gunicorn-19.8.1 pytz-2018.4 remote: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 20, in <module> remote: import psycopg2 as Database remote: ImportError: No module named 'psycopg2' remote: During … -
Django: TemplateDoesNotExist
I'm trying to load a template, but it seems to keep searching for a template in a path that does not exist. I'm looking to load visit_form.html, but it keeps looking in clincher/visit_form, and cannot seem to get rid of the "clincher/" part of the template location. It was previously set up this way, but changed it when I moved my template locations to the respective app. Template Url: <td><a href="{% url 'clincher:visit_form' main.id %}" role="button" class="btn btn-primary btn-xs">New Consult</a></td> Main/Urls.py: from django.contrib import admin from django.urls import include, path from django.views.generic import RedirectView from clincher import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('clincher/', include('clincher.urls'), name='clincher'), path('accounts/', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('', RedirectView.as_view(url='clincher/templates/')), ] Clincher/Urls.py from django.conf.urls import url from . import views from django.urls import path app_name = 'clincher' urlpatterns = [ path('', views.index, name='index'), path('main/', views.MainListView.as_view(), name='main'), path('main/<int:pk>', views.MainDetailView.as_view(), name='main_detail'), path('visit/add/<int:pk>', views.VisitCreate.as_view(), name='visit_form'), ] Views.py class VisitCreate( CreateView): login_url = '/login/' redirect_field_name = 'index' model = Visit fields = [ 'visit_label', 'visit_type', 'visit_progress_notes'] template = 'templates/visit_form.html' def form_valid(self, form): form.instance.fk_visit_user = self.request.user form.instance.fk_visit_main = Main.object.get(self.kwargs['pk']) return super(VisitCreate, self).form_valid(form) def get_success_url(self): return reverse('main_detail', args={'pk': self.object.id}) Settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, … -
Need help converting this structure
I have some UserInvites, where an invite has from and to User properties. E.g., UserInvite1.from = User1 UserInvite1.to = User2 UserInvite2.from = User2 UserInvite2.to = User3 UserInvite3.from = User2 UserInvite3.to = User4 Thus, User1 invited User2, who invited User3 and User4. Given a list of those invites, e.g., [UserInvite1, UserInvite2, UserInvite3], or another means of iterating over them, how can I generate a "hierarchical" list representing those invited? E.g., starting with the "root" User1, I'd like a nested list as such: >>> make_nest_list_from_invites([invites]) [User1, [User2, [User3, User4]] If you're familiar with Django, I'm trying to get from my "invites" to something hierarchical that I can feed to the Django template tag unordered_list Clearly this is something like tree traversal, but I'm stumped at the moment. I tried some recursion-ey stuff, but kept ending up with an extra level of nesting in places that was throwing things off. -
'Friend' has no attribute 'META' error unknown reason - django
I have a view and template that create queries that search through objects in the database. I also have lists that will create a list of usernames based on different querysets. I pass the searched queryset and two lists which are pending and friends. I then check to see if the usernames in the search query are located in the list. if they in the list it will display a different message depending on the list it is located in. if it is not located in any list, it will display a different message. error + trace: AttributeError at /search/ 'Friend' object has no attribute 'META' Request Method: POST Request URL: http://127.0.0.1:8000/search/ Django Version: 2.0.5 Exception Type: AttributeError Exception Value: 'Friend' object has no attribute 'META' Exception Location: /Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages/django/template/context_processors.py in debug, line 40 Python Executable: /Users/omarjandali/anaconda3/envs/MySplit/bin/python Python Version: 3.6.2 Python Path: ['/Users/omarjandali/Desktop/mysplit/mysplit', '/Users/omarjandali/anaconda3/envs/MySplit/lib/python36.zip', '/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6', '/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/lib-dynload', '/Users/omarjandali/anaconda3/envs/MySplit/lib/python3.6/site-packages'] here is the code: if request.method == "POST": search = request.POST['search'] searched = User.objects.filter(username__contains = search).all() searched |= User.objects.filter(first_name__contains = search).all() searched |= User.objects.filter(last_name__contains = search).all() requester = Friend.objects.filter(user = user).filter(requested = True).all() requested = Friend.objects.filter(friend = user.username).filter(requested = True).all() friended = Friend.objects.filter(user = user).filter(accepted = True).all() friender = Friend.objects.filter(friend = user.username).filter(accepted = True).all() … -
How extend user profile on next page django 2.0
I am trying to continue the registration process on the next screen, but after successfully adding the profile to the user's profile, the "profile" is not associated with the previously created user in the admin panel I do not see any information added to the user by this form I do all this while being logged in as admin views.py @login_required def editprofile(request): if request.method == 'POST': form = ProfileForm(request.POST) form.user =request.user if form.is_valid(): profile = form.save() return rerdirect('home') else: form = ProfileForm() return render(request, 'app/login/signup.html', {'form': form}) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) city = models.CharField(max_length=30, blank=True) street = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) phone_number = models.CharField(max_length=12) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('city', 'street', 'birth_date', 'phone_number') -
Reverse for '' not found. '' is not a valid view function or pattern name
I'm trying to add or remove a row into DB, using a button click that redirects back to the same page,, here are my files views.py def favorite_item (request, pk): favitem = get_object_or_404(Item, pk=pk) userfav = Favorite.objects.filter(user=request.user) for items in userfav: if items.item == favitem: items.delete() else: items = Favorite(item=favitem, user=request.user) items .save() return redirect('') urls.py path('<int:pk>/favorite_item/', views.favorite_item, name='favorite_item'), html <a href="{% url 'favorite_item' dress.id %}"> <img src="{% static 'img/gold_star.png' %}"></a> but whenever I click it I get the error : error Reverse for '' not found. '' is not a valid view function or pattern name. -
Error when i click on a category
I'm building an e-commerce website. I have a model with two class(Category and Product), i recently added pagination to my list_view and its working on my products but when i click on the category class, i get an error. from django.shortcuts import render, get_object_or_404 from .models import Category, Product from cart.forms import CartAddProductForm from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.db.models import Q def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) query = request.GET.get("q") if query: products = Product.objects.filter(Q(name__icontains=query) | Q(description__icontains=query)).distinct() paginator = Paginator(products, 10,) page = request.GET.get('page', 2) try: products= paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page products = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results products = paginator.page(paginator.num_pages) if category_slug: category = get_object_or_404(Category, slug = category_slug) products = products.filter(category=Category) return render(request, 'shop/product/list.html', {'category':category, 'categories': categories, 'products': products, 'page': page, }) @login_required def product_detail(request, id, slug): product = get_object_or_404(Product,id=id,slug=slug,available=True) cart_product_form = CartAddProductForm() return render(request,'shop/product/detail.html', {'product': product, 'cart_product_form': cart_product_form}) when i click on product, it works fine and the pagination also works but when i click on category to display other sets of products, it displays this … -
Issue displaying two querysets that loop together and excluding 1 query result - DJANGO
I have a django application and I want to create a search result page. In this page I want a users to be able to search for other users. From the results, if the logged in user is friends with any of the users that came up with the results list, I want it to display friends next to the username. if the search result is not already friends with the logged in user, I want to have a link that will let them send a request to that user that appears next to their name.. I currently have a friends query and results query. I pass them into the template. In the template I loop through the searched results. I then nested the friends query. I then check to see 3 things. If the logged in users username is in the user field, if the current searched username is the same as the current fiend username, I want to display either pending or friend depending on if the friend request is pending or accepted. If a username in the search results does not show up in the friends query, I want to have a friend request link to send … -
How to show only available cars ?iam having two models car and booking
Car model having car attributes Booking model having foreignkey of car . If car is booked how to disable that car for further booking? -
Django db name 'connection' is not defined
i'm making my first project in django + mysql, the problem here is it's notify me that the name 'connection' is not defined. I don't know why. Can't anyone explain me? from django.db import connections import cv2 def detect(request): faceDetect = cv2.CascadeClassifier(BASE_DIR + '/haarcascade_frontalface_default.xml') cam = cv2.VideoCapture(0) # creating recognizer rec = cv2.face.LBPHFaceRecognizer_create(); # loading the training data rec.read(BASE_DIR + '/recognizer/trainingData.yml') getId = 0 font = cv2.FONT_HERSHEY_SIMPLEX maSv = 0 while(True): ret, img = cam.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = faceDetect.detectMultiScale(gray, 1.3, 5) for(x,y,w,h) in faces: cv2.rectangle(img,(x,y),(x+w,y+h), (0,255,0), 2) getId,conf = rec.predict(gray[y:y+h, x:x+w]) #This will predict the id of the face #print conf; if conf<35: maSv = getId cv2.putText(img, str(maSv),(x,y+h), font, 2, (0,255,0),2) maSV = str(maSv) with connection.cursor() as cursor: cursor.callproc('diemdanh', [maSV, '101B1']) else: cv2.putText(img, "Unknown",(x,y+h), font, 2, (0,0,255),2) # Printing that number below the face # @Prams cam image, id, location,font style, color, stroke cv2.imshow("Face",img) if(cv2.waitKey(1) == ord('q')): break elif(maSv != 0): cv2.waitKey(1000) cam.release() cv2.destroyAllWindows() return redirect('/') cam.release() cv2.destroyAllWindows() return redirect('/') -
After uploading image to s3, upload accompanying thumbnail
I can successfully upload my images to s3 via AJAX. However I need to have an accompanying thumbnail in my s3 bucket as well. Here's my s3 upload ajax view: ... session = boto3.Session( aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, ) s3 = session.resource('s3') s3.Bucket('****-bucket').put_object(Key='media/%s' % random_filename, Body=img, ContentType='image/png') return HttpResponse() What is the best way to create and upload a thumbnail from my code? Do I add another put_object under my current one? If so, how do I implement a thumbnail generator like PIL? I tried to replicate this answer however the setup is quite different to mine. Or is it viable to use a AWS lambda function instead? Any advice appreciated. -
Error: Using the URLconf defined in helloapp.urls, can't figure out solution
There was a question similar here but I couldn't exactly find my soltution from that. Plus I want to understand how to solve this and not just get solution haha. Please let me know if I should rephrase or include anything else! I am following this tutorial and I have reached the part where I need to runserver. But it pops up with an error and I'm not sure what to do next to solve this. Error page saying: "Using the URLconf defined in helloapp.urls, Django tried these URL patterns, in this order: admin/ , ^helloapp/ The empty path didn't match any of these." My project is as follows helloapp: hello app, howdy helloapp/urls.py from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() from django.urls import path urlpatterns = [ path(r'admin/', admin.site.urls), url(r'^helloapp/', include('howdy.urls')), ] howdy/views.py from django.shortcuts import render # howdy/views.py from django.shortcuts import render from django.views.generic import TemplateView #Create your views here class HomePageView(TemplateView): def get(self, request, **kwargs): return render(request, 'index.html', context=None) howdy/templates/index.html <!-- howdy/templates/index.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Howdy!</title> </head> <body> <h1>Howdy! I am Learning Django!</h1> </body> howdy/urls.py #howdy/urls.py from django.conf.urls import url from howdy import views urlpatterns = [ url(r'^$', views.HomePageView.as_view()), ] -
How to rescue django project from unusable virtualenv
I have a basic site using django/wagtail, that I had in a virtualenv. I was mainly working off of a nas device with an ARM processor. I transferred it recently to a virtual machine on my x86-64 laptop and wass unable to use it. I learned why, learned the hard way that virtualenv is not a packaging mechanism. I just wondering what the 'best' way would be to rescue the django project and maybe somehow get a list of pip packages installed to the virtualenv (as pip freeze -r won't run due to the pip binary being for ARM). Is there an easy way to do what I am asking, or would I be better off just trying to copy the django files and recreating the virtualenv?