Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django queryset gives me an syntaxerror as result
I'm trying to import a model in views.py so i can add a modelobject to context which will render to the html template , but instead it returns an syntaxerror. This is what views.py looks like: from django.shortcuts import render from .models import Food def detail_view(request): print request food = Food.objects.all().first() template = "detail_view.html" context = { "title": "Hello , Detail" "food": food } return render(request, template, context) This is what models.py looks like: from django.db import models # Create your models here. class Food(models.Model): title = models.CharField(max_length=20) description = models.TextField(null=True, default="Description will be placed here") price = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) def __unicode__(self): return self.title Note: im using django 1.8.6 and python 2.7 -
KeyError: 'password1': password1 = self.cleaned_data['password1']
I am trying to implement registration in Django and faced with error: forms.py line 17, in clean_password KeyError: 'password1': password1 = self.cleaned_data['password1'] How can I solve the error? Full code of the application located here (branch Login-version-2-site ): https://github.com/mascai/reg_app/tree/Login-version-2-site models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.dispatch import Signal from .utilities import send_activation_notification class AdvUser(AbstractUser): is_activated = models.BooleanField(default=True, db_index=True, verbose_name='Пpoшeл активацию?') send_messages = models.BooleanField(default=True, verbose_name='Слать оповещения о новых комментариях?') class Meta(AbstractUser.Meta): pass user_registrated = Signal(providing_args=['instance']) def user_registrated_dispatcher(sender, **kwargs): send_activation_notification(kwargs['instance']) user_registrated.connect(user_registrated_dispatcher) forms.py class RegisterUserForm(forms.ModelForm): email = forms.EmailField(required=True, label="Email address") password1 = forms.CharField(label="Password", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) password2 = forms.CharField(label="Password", widget=PasswordInput, help_text=password_validation.password_validators_help_text_html()) def clean_password(self): password1 = self.cleaned_data['password1'] if password1: password_validation.validate_password(password1) return password1 def clean(self): super().clean() password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: errors = {'password2': ValidationError('Введённые пароли не совпадают', code='password_mismatch')} raise ValidationError(errors) else: return self.cleaned_data def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data['password1']) user.is_active = False user.is_activated = False if commit: user.save() user_registrated.send(RegisterUserForm, isinstance=user) return user class Meta: model = AdvUser fields = ('username', 'email', 'password', 'password2', 'first_name', 'last_name', 'send_messages') urls.py from .views import BBLoginView, BBLogoutView, profile, RegisterUserView, RegisterDoneView, user_activate urlpatterns = [ path('', views.post_list, name='post_list'), path('accounts/login/', BBLoginView.as_view(), name='login'), path('accounts/profile/', profile, name='profile'), path('accounts/logout/', BBLogoutView.as_view(), name='logout'), … -
How to setup path (urls) for multiple Django applications in a single Django project
I have a single Django project which has two different Django applications, MyApp1 and MyApp2 (changed their names). The structure is like this: MyProject MyApp1 static templates urls.py views.py ... MyProject settings.py urls.py ... I wrote the MyApp2 as a separate application in a different Django project and integrated it with the MyProject project (pip install MyApp2). Here is the installed apps in the settings.py file: # Application definition INSTALLED_APPS = [ 'MyApp1', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MyApp2', ] These are the following paths (urls.py) of the MyProject. from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('myapp1/', include('myapp1.urls')), path('', include('myapp1.urls')), path('myapp2/',include('myapp2.urls')), ] These are the following paths (urls.py) of the MyApp1: from django.urls import path from . import views from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('about/', views.about, name='about'), path('contact/', views.contact, name='contact'), ] These are the following paths (urls.py) of the MyApp2: from django.urls import path from . import views urlpatterns = [ path('', views.login, name='login'), path('index', views.home, name='home'), path('dashboard_output', views.dashboard_output, name='dashboard_output'), path('login', views.login, name='login'), ] On the browser, if I type http://127.0.0.1:8000/ or http://127.0.0.1:8000/myapp1 I get the view of the MyApp1. On the browser, … -
How to set sessionid in cockie in Angular 7, to save session_key for multiple async requests?
I'm setting a Django server which exposes an endpoint, that receives many post calls (20/second) from the same client (an angular application running on http://localhost:4200/). I need to save the session_key for this client(), since there are some session variables that gets updated with each request. The problem is that the session is not getting saved on client's side. Each request comes with session_key = None From postman it saves the session perfectly, and all works as expected. I noticed that postman sets a cookie from the client in the first call: Cookie: sessionid=en2ghiz6df8xoy4v45fhqatx0c820bqb; path=/; domain=localhost; HttpOnly; Expires=Sat, 09 Nov 2019 23:41:56 GMT; The following snippet show how the django server set the id: def detect(request): # initialize the data dictionary to be returned by the request if request.method == "POST": print(request.session.session_key) if not request.session.exists(request.session.session_key): request.session.save() print(request.session.session_key) The desired result output(this is using postman) [26/Oct/2019 22:33:37] "GET /get_result/ HTTP/1.1" 500 70124 #comes with an initial session_key id and don't needs to create new one #maintains the session_key for next requests en2ghiz6df8xoy4v45fhqatx0c820bqb [27/Oct/2019 16:23:18] "POST /face_detection/detect/?= HTTP/1.1" 200 0 en2ghiz6df8xoy4v45fhqatx0c820bqb [27/Oct/2019 16:23:21] "POST /face_detection/detect/?= HTTP/1.1" 200 0 en2ghiz6df8xoy4v45fhqatx0c820bqb [27/Oct/2019 16:23:24] "POST /face_detection/detect/?= HTTP/1.1" 200 0 Actual result ouput using Angular client: … -
Can I make the automatic collection field before click submit in Django?
Can I make the automatic collection field before click submit in form Django? I illustrate the idea with the attached drawingenter image description here -
Django Writing database migrations forward function issue
I'm trying to add custom migration to django app. I want that the custom migration wouldn't work with "default" database and another custom migration works with only "default" database. I apply method suggested in django documentation but migration commands never worked. How can i fix this issue? Thanks for helps. Django documentation page: [https://docs.djangoproject.com/en/2.2/howto/writing-migrations/][1] My code (0001_initial.py,only works with "default" database): from django.db import migrations, models def forwards(apps, schema_editor): if schema_editor.connection.alias == 'default': migrations.CreateModel( name='Planets', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255)), ('description', models.TextField(blank=True)), ], ), class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.RunPython(forwards), ] Other migration (only works with non "default" databases): from django.db import migrations, models def forwards(apps, schema_editor): if schema_editor.connection.alias != 'default': migrations.CreateModel( name='data_sources', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('sql_query', models.TextField(default='')), ], ), migrations.CreateModel( name='query_history', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('query', models.TextField()), ('date', models.DateField(auto_now_add=True)), ], ), class Migration(migrations.Migration): dependencies = [ ('universe','0001_initial') ] operations = [ migrations.RunPython(forwards), ] -
How to create correct notifications with django getstream?
I create notifications system with getstream.io in Django and works good but, in one situation I don't know how to correctly do this. I have Django and this app: https://github.com/GetStream/stream-django Normally I create notification as in tutorial in link above, and this work well. class Follow(models.Model, Activity): @property def activity_notify(self): return [feed_manager.get_notification_feed(self.target_user.id)] Now I need something difficult. I have 3 models. class Goal(models.Model, Activity): title = models.CharField(max_length=255, verbose_name='Tytuł') image = models.ImageField(blank=True, verbose_name='Tło') body = HTMLField(verbose_name='Treść') votes = GenericRelation(LikeDislike, related_query_name='goalvotes') created_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE) class Joined(models.Model, Activity): goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name='joined_goal') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='joined_users') created_at = models.DateTimeField(auto_now_add=True) and class Comment(models.Model, Activity): body = models.TextField() created_at = models.DateTimeField(auto_now_add=True) author = models.ForeignKey(User, on_delete=CASCADE) and my goal is to send notification about new comment in goal to all users who already joined to goal. I try something like this: @property def activity_notify(self): return [feed_manager.get_notification_feed(Joined.user.id)] I know this is wrong, but I have no other idea how to do this. Maybe someone have solution. -
django error in http://127.0.0.1:8000/ Page not found (404)
Sorry for my basic question but I'm learning and I can't identify the error *Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in proyectoapettito.urls, Django tried these URL patterns, in this order: admin/ AppApettito/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.* whit /index *Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/index Using the URLconf defined in proyectoapettito.urls, Django tried these URL patterns, in this order: admin/ AppApettito/ The current path, index, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.* url app from django.urls import path from . import views urlpatterns=[ path('',views.index, name='index'), ] url project from django.contrib import admin from django.urls import path from django.urls import include urlpatterns=[ path('admin/',admin.site.urls), path('AppApettito/',include('AppApettito.urls')), ] views app from django.shortcuts import render from .models import Menu # Create your views here. def index(request): return render(request, 'AppApettito/index.html', {}) -
zip and formset together in django template
im trying to use formset_factory and something from my db in zip and use it in to template here is my form: class class_attandance_form(forms.ModelForm): choise1 = [(True, 'ح'), (False, 'غ')] choise2 = [('مثبت', 'مثبت'), ('منفی', 'منفی')] attendance = forms.ChoiceField(required=True, choices=choise1) activity = forms.ChoiceField(required=False, choices=choise2) score = forms.CharField(required=False, max_length=3) user = forms.CharField(required=False,max_length=20) class Meta: model = Class_Book fields = ('activity','attendance','score','user') and here is my view: def class_attendance(request): term = Term.objects.filter(lesson__in=[1,]) form1 = formset_factory(class_attandance_form,max_num=len(term),extra=len(term)) form = form1() term_form = zip(list(term), list(form)) if request.method == 'POST': query = form1(request.POST or None) if query.is_valid(): q = query.cleaned_data print(q) return render(request,'teacher/class_attendance.html',{'term_form':term_form}) and my temp is : <form role="form" method="post"> {% csrf_token %} <table cellspacing="0" class="table"> <thead> <tr> <th>ردیف</th> <th>نام و نام خانوادگی</th> <th>حضور و غیاب</th> <th colspan="2">نمره</th> </tr> </thead> <tbody> {% for term, form in term_form %} <tr class="class_book" id="{{ term.id }}"> <td>{{ forloop.counter }}</td> <td>{{ term.student.first_name }} {{ term.student.last_name }}</td> <td> {{ form.attendance }} </td> <td> {{ form.activity }} </td> <td> {{ form.score }} </td> </tr> {{ form.user }} <script> $('#id_form-{{ forloop.counter0 }}-user').val({{ term.id }}) </script> {% endfor %} </tbody> </table> <button id="submit" class="button" type="submit">ثبت</button> </form> why when i use query = form1(request.POST or None) i got this error "ManagementForm Data is Missing When … -
How Can I Declare File in travis config file?
I created simple django project and i stored secret key, variable etc. in keys.json file. It gives this error when i try to build project: FileNotFoundError: [Errno 2] No such file or directory: 'keys.json' How can i fix it. My .travis.yml file: python: - "3.7" install: - pip install -r requirements.txt script: - python manage.py test - python manage.py runserver 0.0.0.0:8000 -
How to use FilePond in Django project
Background: I have two models: SellingItem and SellingItemImages. SellingItemImages has a custom FileField that can take multiple files. By putting two forms(itemform and imageform) under single element (enctype="multipart/form-data"), I was able to allow users to upload multiple images. Now, I want to incorporate client side image optimization and better UI. I tried out filepond but am facing some challenges. I organized this post by showing django code without filepond showing code with filepond what I accomplished with filepond so far questions on what to do next ** 1)django code without filepond.** models.py # models.py class SellingItem(models.Model): seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=200) description = models.CharField(max_length= 500, null=True, blank=True) price = models.IntegerField(default=0) class SellingItemImages(models.Model): sellingitem = models.ForeignKey(SellingItem, default = None, on_delete=models.CASCADE, related_name='images') image = ContentTypeRestrictedFileField(content_types=['image/png', 'image/jpeg','image/jpg'],blank=True, max_upload_size=5242880) #ContentTypeRestrictedFileField is a custom FileField. Here is forms.py class SellingItemForm(forms.ModelForm): class Meta: model = SellingItem fields = ('name', 'description', 'price') class SellingItemImagesForm(forms.ModelForm): class Meta: model = SellingItemImages fields= ('image',) widgets = { 'image': forms.FileInput(attrs={'multiple':True,}), } Here is views.py @login_required def post_newitem(request): if request.method == 'POST': itemform = SellingItemForm(request.POST) imageform = SellingItemImagesForm(request.POST, request.FILES) if '_cancel' in request.POST: itemform = SellingItemForm() imageform = SellingItemImagesForm() return render(request, 'market/post_newitem.html', {'itemform': itemform, 'imageform': imageform}) else: if '_publish' in … -
Django: Assign a group to new user per type
I'm using table inheritance in my authentication system, so the User model has 4 types inheriting from it. normaladmin, manager, operator, worker, each one has its own table since they have different attributes, and there is a group for each table. so when anyone registers, he selects his group, and when the instance is created i need to assign it to its group. i have seen this, it suits the problem but not exactly my case, because i need to specify to which group i want to assign the instance to. so i need help on how i can do this, specify the group name to which i want to assign the instance. -
Need workaround for limit in Django mysql query
This line does not work: specific_info = Special.objects.filter(specialid=pk).order_by('description')[:1] This is the error that I get after switching from SQLite to MYSQL: (1235, "This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'") Is there a workaround to do limits in Django with a MYSQL Database? -
Unable to load celery application
I am having the following error: Error: Unable to load celery application. The module teste was not found. when calling the command line: celery -A teste worker -l info -P gevent in other forum questions, it is recommended to change the name of celery.py, check the directories, and they ask if there is a init.py None of those answers suited my issue. I'd appreciate if you could help me and explain to me what I might be doing wrong (not keen on neither Python nor Django just yet). Here's the celery.py inside my teste app (folder) # from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'teste.settings') app = Celery('teste') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() # @app.task(bind=True) # def debug_task(self): # print('Request: {0!r}'.format(self.request)) Here's the init.py # from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) -
Avoid n+1 queries in Django admin list view
I have a Django model: class Book(models.Model): title = models.CharField(max_length=30) @property def slug(self): return slugify(self.title) Now if I add slug field to admin list_display, there will be a separated query for each instance. How to make just one query for all instances? I tried to use select_related in the ModelAdmin class, but I did not get it working. -
python manage.py createsuperuser works on Mac, but does not work on windows
I have been going through the Django tutorial in the following link. I have completed this on a Mac, however I am hitting problems on windows 10: djangoproject In Tutorial part 2, when it comes to creating a new superuser, it fails. If I run the following on a Mac, I can create a new superuser. It fails when I run a similar command on windows. I have tried running both of the following on windows: ``` source venv/bin/activate python manage.py createsuperuser ``` ``` .\venv\Scripts\activate py manage.py createsuperuser ``` Package (pip list): ``` Package Version ----------- ------- Django 2.2.6 docutils 0.15.2 pip 19.3.1 pycodestyle 2.5.0 pytz 2019.3 setuptools 41.4.0 sqlparse 0.3.0 wheel 0.33.6 ``` The db.sqlite3 database is present, and as far as I can tell has a reasonable structure (there are lots of Django specific tables). I expect to create a new superuser, but instead get this output: Traceback (most recent call last): File "C:\Users\Mark\Documents\Development\Python\PYTHON---DJANGO---TUTORIAL\venv\lib\site-packages\django\contrib\auth\password_validation.py", line 26, in get_password_validators klass = import_string(validator['NAME']) File "C:\Users\Mark\Documents\Development\Python\PYTHON---DJANGO---TUTORIAL\venv\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\Mark\Documents\Development\Python\PYTHON---DJANGO---TUTORIAL\venv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line … -
Is there a way to get only specific fields in a queryset after serialization data, without create a different serializer in drf?
i need to do a query where i want to get specific fields, then serializate it and keep only the specific fields which I got in the query. models.py class Search(models.Model): NEUTRAL = 'None' POSITIVE = 'P' NEGATIVE = 'N' POLARITY_CHOICES = [ (NEUTRAL, 'Neutral'), (POSITIVE, 'Positive'), (NEGATIVE, 'Negative'), ] user = models.ForeignKey(User,related_name='searched_user_id',on_delete=models.CASCADE) word = models.CharField( max_length = 100) social_network = models.ForeignKey(SocialNetwork,related_name='search_social_network_id',on_delete=models.CASCADE) polarity = models.CharField( max_length=4, choices=POLARITY_CHOICES, default=NEUTRAL, ) sentiment_analysis_percentage = models.FloatField(default=0) topic = models.ForeignKey(Topic,related_name='search_topic_id',on_delete=models.CASCADE) liked = models.IntegerField(default=0) shared = models.IntegerField(default=0) is_active = models.BooleanField(default=True) is_deleted = models.BooleanField(default=False) updated_date=models.DateTimeField(auto_now=True) searched_date = models.DateTimeField(auto_now_add=True) serializers.py class SearchSerializer(serializers.ModelSerializer): searched_date = serializers.DateTimeField(format="%d-%m-%Y") class Meta: model = Search fields = ('__all__') class RecentSearchSerializer(serializers.ModelSerializer): searched_date = serializers.DateTimeField(format="%d-%m-%Y") class Meta: model = Search fields = ('user','social_network','word','searched_date') class SentimentAnalysisSerializer(serializers.ModelSerializer): searched_date = serializers.DateTimeField(format="%d-%m-%Y") class Meta: model = Search fields = ('polarity','searched_date','sentiment_analysis_percentage') SearchSerializer is the main serializer for search, RecentSearchSerializer is the serializer to pass data and filtering in the DRF api view, and finally I created SentimentAnalysisSerializer to keep the specific fields that I need: api.py class SearchViewSet(viewsets.ModelViewSet): queryset = Search.objects.filter( is_active=True, is_deleted=False ).order_by('id') permission_classes = [ permissions.AllowAny ] serializer_class = SearchSerializer pagination_class = StandardResultsSetPagination def __init__(self,*args, **kwargs): self.response_data = {'error': [], 'data': {}} self.code = 0 def get_serializer_class(self): if … -
Django 2.2 i18n urlpatterns not being translated
I'm curious as if someone have tested using the i18n functionality of Django in the latest Django version? I'm trying to internationalize my urlpatterns as following: urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')) ] urlpatterns += i18n_patterns( path('', include('apps.frontpage.urls', namespace='frontpage')), path(_('journal/'), include('apps.journal.urls', namespace='journal')), path(_('projects/'), include('apps.projects.urls', namespace='projects')), path(_('software/'), include('apps.software.urls', namespace='software')), path('administration/', admin.site.urls), ) using this .po file: #: core/urls.py:22 msgid "journal/" msgstr "dagbok/" #: core/urls.py:23 msgid "projects/" msgstr "prosjekter/" #: core/urls.py:24 msgid "software/" msgstr "programvare/" The .po and .mo files are being generated and detected as the HTML menu gets translated: <li><a href="{% url 'frontpage:index' %}"><i class="fas fa-home fa-fw"></i> {% trans "Home" %}</a></li> <li><a href="{% url 'journal:index' %}"><i class="fas fa-book fa-fw"></i> {% trans "Journal" %}</a></li> <li><a href="{% url 'projects:index' %}"><i class="fas fa-project-diagram fa-fw"></i> {% trans "Projects" %}</a></li> <li><a href="{% url 'software:index' %}"><i class="fas fa-hdd fa-fw"></i> {% trans "Software" %}</a></li> However, my urls are still not being translated. I'm not quite sure if I have done something wrong, or if this functionality is actually bugged in the latest Django version. Do I need to configure anything else than LOCALE_PATHS = [ os.path.join(BASE_DIR, 'shared/locale') ] for it to detect locale directories within applications? or is this done automatically by Django? -
ERRO DE EDITAR UN ID con Fk en DJANGO 2.2
Tengo un pequeño problema cuando yo quiero editar mi modelo con un relación fk django me lanza esto: enter image description here Este es mi funcion editar enter image description here Este es mi templete donde muestro la el id a editar enter image description here -
How to fix ‘ModuleNotFoundError: No module named 'pkgutil' error in pipenv
Im want creating virtual environment in my project Failed to create virtual environment. PS C:\Users\андрей\Desktop\Project> pipenv install Creating a virtualenv for this project… Pipfile: C:\Users\андрей\Pipfile Using c:\users\андрей\appdata\local\programs\python\python38-32\python.exe (3.8.0) to create virtualenv… [ ] Creating virtual environment...Already using interpreter c:\users\андрей\appdata\local\programs\python\python38-32\python.exe Using base prefix 'c:\users\андрей\appdata\local\programs\python\python38-32' New python executable in C:\Users\андрей.virtualenvs\андрей-TUBSFJkQ\Scripts\python.exe Command C:\Users\андрей.vir...Q\Scripts\python.exe -m pip config list had error code 1 Installing setuptools, pip, wheel... Complete output from command C:\Users\андрей.vir...Q\Scripts\python.exe - setuptools pip wheel: Traceback (most recent call last): File "", line 3, in return _run_code(code, main_globals, None, File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\runpy.py", line 85, in _run_code exec(code, run_globals) File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv.py", line 2628, in main() File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv.py", line 860, in main create_environment( File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv.py", line 1173, in create_environment install_wheel(to_install, py_executable, search_dirs, download=download) File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv.py", line 1019, in install_wheel _install_wheel_with_search_dir(download, project_names, py_executable, search_dirs) File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv.py", line 1110, in _install_wheel_with_search_dir call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script) File "c:\users\андрей\appdata\local\programs\python\python38-32\lib\site-packages\virtualenv.py", line 963, in call_subprocess raise OSError("Command {} failed with error code {}".format(cmd_desc, proc.returncode)) OSError: Command C:\Users\андрей.vir...Q\Scripts\python.exe - setuptools pip wheel failed with error code 1 -
I am getting the following error when open the admin panel of the project Note : OperationalError at /admin/app/contact/
OperationalError at /admin/app/contact/ no such table: app_contact Request Method: GET Request URL: http://127.0.0.1:8000/admin/app/contact/ Django Version: 2.2.6 Exception Type: OperationalError Exception Value: no such table: app_contact Exception Location: C:\Users\cvm\Desktop\CNumber\env\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: C:\Users\cvm\Desktop\CNumber\env\Scripts\python.exe Python Version: 3.8.0 Python Path: ['C:\Users\cvm\Desktop\CNumber', 'C:\Users\cvm\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\cvm\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\cvm\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\cvm\AppData\Local\Programs\Python\Python38-32', 'C:\Users\cvm\Desktop\CNumber\env', 'C:\Users\cvm\Desktop\CNumber\env\lib\site-packages'] Server time: Sun, 27 Oct 2019 16:43:09 +0000 -
Destroying file after HTTP response in Django
I'm now making website that downloads certain images from other website, zip files, and let users download the zip file. Everything works great, but I have no way to delete zip file from server, which has to be deleted after users download it. I tried deleting temp directory that contains zip file with shutil.rmtree, but I couldn't find way to run it after HTTPResponse. Here is my code in views.py. zipdir = condown(idx)#condown creates zip file in zipdir logging.info(os.path.basename(zipdir)) if os.path.exists(zipdir): with open(zipdir, 'rb') as fh: response = HttpResponse(fh.read(), content_type="multipart/form-data") response['Content-Disposition'] = 'inline; filename=download.zip' return response raise Http404 Thanks in advance. -
How to get input values from Django dynamically generated inline forms
I have a parent / child scenario (something like order/order items) wherein I have the child forms generated dynamically (with option to add form rows at runtime). I tried to get the values input in the fields using jQuery. I am able to do this for the header (parent) forms using the element's "id". But I am unable to do so with the inline (child) formset fields. The child forms are being generated by looping thru' formset object in management_form in the template (can't find the "id"s for the child fields). My question is: How do I assign "id"s to the child forms (so that then I may query them to get the value assigned to them Or is there any other way/s I can get the input values I have scoured thru' this site (including those suggested as I was typing out this query) as well as various others, but for the life of me unable to get a lead. Any possible lead? -
How can i add fields in my CustomUserCreationForm?
Forms.py class CustomUserCreationForm(UserCreationForm): #phone_number = forms.CharField(max_length = 100) class Meta: model = CustomUser fields = ('username', 'email','first_name','last_name', 'phone_number', 'middle_name') Admin.py class CustomUserAdmin(UserAdmin): model = CustomUser add_form = CustomUserCreationForm form = CustomUserChangeForm fieldsets = ( (('User'), {'fields': ('username', 'email', 'phone_number', 'first_name', 'last_name', 'middle_name', 'is_staff', 'is_superuser', 'is_active', 'is_parent', 'is_teacher')}), ) Models.py (All the fields in Admin.py are declared here without errors) class CustomUser(AbstractUser): phone_number = models.CharField(max_length = 100, blank=True, null = True) first_name = models.CharField(max_length = 100, default = '') last_name = models.CharField(max_length = 100, default = '') AddNewUser Image Here As you can see, I tried adding a Charfield directly in CustomUserCreationForm and I also tried adding fields but it just would not appear whenever I add new user. -
my apache config is not working getting error '500 Internal server error'
I am trying to deploy my django project on apache2 but its giving me an error '500 internal server error'. Here is my configuration file myproject.conf <VirtualHost *:80> ServerAdmin amol@myfirstdjango.localhost ServerName myfirstdjango.localhost ServerAlias www.myfirstdjango.localhost DocumentRoot /var/www/lms_project/Django-CRM ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/lms_project/static <Directory /var/www/lms_project/static> Require all granted </Directory> Alias /static /var/www/lms_project/media <Directory /var/www/lms_project/media> Require all granted </Directory> <Directory /var/www/lms_project/Django-CRM/crm> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess lms_project python-path=/var/www/lms_project python-home=/var/www/lms_project/env WSGIProcessGroup lms_project WSGIScriptAlias / /var/www/lms_project/Django-CRM/crm/wsgi.py </VirtualHost> my project is in /var/www/lms_project/Django-CRM #this folder contains manage.py virtual environment is in /var/www/lms_project my apache logs [Sun Oct 27 21:00:36.472014 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] wtforms.validators.ValidationError: The CSRF session token is missing. [Sun Oct 27 21:00:36.472022 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] [Sun Oct 27 21:00:36.472030 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] During handling of the above exception, another exception occurred: [Sun Oct 27 21:00:36.472038 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] [Sun Oct 27 21:00:36.472046 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] Traceback (most recent call last): [Sun Oct 27 21:00:36.472054 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] File "/usr/local/lib/python3.6/dist-packages/flask/app.py", line 1947, in full_dispatch_request [Sun Oct 27 21:00:36.472062 2019] [wsgi:error] [pid 3409:tid 139766507882240] [remote ::1:43628] rv …