Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
- 
        how to pass parameters from views to the template in django?i have a function that create object and i need to display the value on the template i know that i can pass the parameter in dictionary but it did not work and the template is empty. but if i print the value in the views it display the correct result. views.py def createFolder(request): if request.method == 'POST': FolderNum = request.POST['FolderNum'] print("folder number :",FolderNum ) dbFolder = testFolder.objects.create(folder_num = FolderNum) print("dbfolder = ", dbFolder.id) print("folder number after save====", dbFolder.folder_num) return render(request,'dropDown.html',{"dbFolder":dbFolder}) dropDown.html <h1> folder number is {{dbFolder.folder_num}}</h1> <h1> folder id is {{dbFolder.id}}</h1>
- 
        Is it possible to connect a model object to a celery task?I need to connect a celery task to a model objects. For example, I need to create an object of a model class AuthorPrice(models.Model): author = models.Charfield(default=0) price = models.FloatField(default=0) I have a task.py app = Celery() @app.task def create(): new = AuthorPrice.object.create() new.author = John new.price = 30 new.save() I call a task in view create.apply_async(eta.datetime(2019, 07, 31, 15, 56)) so far, everything is ok but, if i need to revoke or edit this task is possible to connect it at my model like a ForeignKey? ty
- 
        Displayed haystack search result in template using result.field_name shows within square brackets issueI'm able to display the search result using django haystack with solr as back end. But the issue is that the displayed values that has been indexed by search engine is been got displayed within the square brackets as in json eg : ['User name']. How to display this properly? search_indexes.py class ShowcaseSearch(indexes.SearchIndex,indexes.Indexable): text = indexes.EdgeNgramField(document=True,use_template=True) showcase_name = indexes.CharField(model_attr='showcase_name') created_date= indexes.CharField(model_attr='created_date') status = indexes.CharField(model_attr='status') created_by = indexes.CharField(model_attr='created_by') def get_model(self): return Showcase def index_queryset(self, using=None): qs=self.get_model().objects.exclude(status='P')\ .filter(is_active='Y') return qs showcase_text.txt {{object.showcase_name|safe}} {{object.created_date|safe}} {{object.reg_id.reg_name|safe}} search.html {% for result in object_list %} <tr> <td><a href="{% url 'showcase:showcase_applicant_view' pk=result.object.id %}">{{result.showcase_name}}</a></td> <td>{{result.created_date}}</td> <td>{{result.created_by}}</td> </tr> {% empty %} <p>No results found.</p> {% endfor %} Resulting slor index file { "id":"showcase.showcase.31", "django_ct":["showcase.showcase"], "django_id":[31], "text":["Test 52\nJuly 19, 2019, 6:58 p.m.\nInvestor"], "showcase_name":["Test 52"], "created_date":["2019-07-19T13:28:36.710Z"], "status":["N"], "created_by":["test_tt@abc.in"], "_version_":1640491605421981702}, I expect the result.showcase_name should display corresponding name Test 52, but instead it is displayed with in square brackets like ['Test 52']. Also please let me know how to get showcase id from text field of solr file, instead of retrieving from model instance using result.object.id.
- 
        How to put an item in a context list that comes from related class?In a View context field I want to show a new entry from related class. Context list uses some type of format that I can't comprehend, so I need some help. I have tried showing related information directly on the list, but I am missing attribute that should be provided to the template (I am talking about 'verbose_name') views.py: class UpdateSimple(UserPassesTestRaiseException, UpdateView): model = Subjects def get_context_data(self, **kwargs): context = super(UpdateSimple, self).get_context_data(**kwargs) context['readonly_fields'] = ['program', 'title', self.object.program.type] print(context['readonly_fields']) # For this I get: ['program', 'title', Fulltime] models.py: class Subjects(models.Model): title = models.CharField(max_length=160, verbose_name="Title") program = models.ForeignKey(Program, verbose_name="Program") def __str__(self): return self.title class Program(models.Model): title = models.CharField(max_length=160, verbose_name="Program") type = models.CharField(max_length=64, verbose_name='Type') def __str__(self): return self.title I want to get something similar in this part: context['readonly_fields'] = ['program', 'title', 'type'] print(context['readonly_fields']) # For this I want to get: ['program', 'title', 'type'] On the page it should show result: form.instance - verbose_name form.instance - value Program: program1 Title: subjectTitle1 Type: Fulltime
- 
        'mkvirtualenv' is not recognized as an internal or external command, operable program or batch fileWhen I gave the following commands error occured. pip install virtualenv (WORKED) pip install virtualenvwrapper-win (WORKED) mkvirtualenv env2 (ERROR as follows) 'mkvirtualenv' is not recognized as an internal or external command, operable program or batch file. Can anyone provide me solution?
- 
        DRF: What validation takes place when calling <model_instance>.save()?I've read a lot of posts here in SO, and the more I read, the more confused I get. This came about from creating unitttests, where I often need to create an instance of a model, then change fields, and call instance.save(). But it's not just for unittests. For my multi-tenant site, there's a create_tenant() method (for example), which eventually calls create(). And when updating a tenant, some "save()" method is called, though it's not clear in my mind yet how, when, or which one is called. The first time I tried saving an instance in my unittests, the validations didn't run - my test was checking for raising a ValidationError, and I didn't get that assertion error. I then created a save() method in my model class and called self.full_clean(). That caused the validations to run, but I got this error: Traceback (most recent call last): File "/code/src/virticl_api/tenants/tests/test_models.py", line 110, in test_invalid_schema_names self.test_tenant.save() File "/code/src/virticl_api/tenants/models.py", line 230, in save self.full_clean() # Run validations File "/usr/local/lib/python3.6/site-packages/django/db/models/base.py", line 1152, in full_clean raise ValidationError(errors) django.core.exceptions.ValidationError: {'schema_name': ['This field cannot be blank.']} However, this didn't trigger the unittest assertion either because that is the wrong ValidationError. Note that it is: django.core.exceptions.ValidationError My test …
- 
        How to fix broken link from Django MEDIA_ROOT?I am attempting to show my image on website which is part of a postgresql DB which is connected to Django. I upload the file to the Django admin upload screen and have my model set up. However, I keep on getting a broken link for the picture. My images folder is also in the base directory of my project. I have tried to manipulate the root many times. I have also tried to use different images and types of images. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url('', jobs.views.home, name='home'), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) home.html <img src = "{{ job.image.url }}" class="card-img-top" > Am getting this get request "GET /media/images/22195497_10214668197162885_8935384055220872583_n.jpg HTTP/1.1" 200" Which is the correct image I want to show.
- 
        Django 'pip install django-heroku'(psycopg2) error is blocking deployment to HerokuI am setting up a new Django project to deploy on Heroku, however when I am following the Django Heroku deployment guide I come across an error during 'pip install django-heroku'. I am running on: OS: MacOS Mojave 10.14.6 virtualenv: python3 pip freeze output: (env) MacBook-Pro:testing_django sudoxx2$ pip freeze dj-database-url==0.5.0 Django==2.2.3 gunicorn==19.9.0 psycopg2-binary==2.8.3 pytz==2019.1 sqlparse==0.3.0 whitenoise==4.1.3 Here is the error output after executing the pip install django-heroku command: (env) MacBook-Pro:testing_django sudoxx2$ pip install psycopg2-binary Collecting psycopg2-binary Using cached https://files.pythonhosted.org/packages/ee/ed/2772267467ba5c21a73d37149da0b49a4343c6646d501dbb1450b492d40a/psycopg2_binary-2.8.3-cp37-cp37m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl Installing collected packages: psycopg2-binary Successfully installed psycopg2-binary-2.8.3 (env) MacBook-Pro:testing_django sudoxx2$ pip install django-heroku Collecting django-heroku Using cached https://files.pythonhosted.org/packages/59/af/5475a876c5addd5a3494db47d9f7be93cc14d3a7603542b194572791b6c6/django_heroku-0.3.1-py2.py3-none-any.whl Collecting psycopg2 (from django-heroku) Using cached https://files.pythonhosted.org/packages/5c/1c/6997288da181277a0c29bc39a5f9143ff20b8c99f2a7d059cfb55163e165/psycopg2-2.8.3.tar.gz Requirement already satisfied: whitenoise in /Users/sudoxx2/Documents/github/delete_copy/env/lib/python3.7/site-packages (from django-heroku) (4.1.3) Requirement already satisfied: django in /Users/sudoxx2/Documents/github/delete_copy/env/lib/python3.7/site-packages (from django-heroku) (2.2.3) Requirement already satisfied: dj-database-url>=0.5.0 in /Users/sudoxx2/Documents/github/delete_copy/env/lib/python3.7/site-packages (from django-heroku) (0.5.0) Requirement already satisfied: sqlparse in /Users/sudoxx2/Documents/github/delete_copy/env/lib/python3.7/site-packages (from django->django-heroku) (0.3.0) Requirement already satisfied: pytz in /Users/sudoxx2/Documents/github/delete_copy/env/lib/python3.7/site-packages (from django->django-heroku) (2019.1) Installing collected packages: psycopg2, django-heroku Running setup.py install for psycopg2 ... error ERROR: Command errored out with exit status 1: command: /Users/sudoxx2/Documents/github/delete_copy/env/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/4d/s84v7k6d1dx_m_6qbd1wfbz80000gp/T/pip-install-cq6yuehb/psycopg2/setup.py'"'"'; __file__='"'"'/private/var/folders/4d/s84v7k6d1dx_m_6qbd1wfbz80000gp/T/pip-install-cq6yuehb/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/4d/s84v7k6d1dx_m_6qbd1wfbz80000gp/T/pip-record-tyidyv7j/install-record.txt --single-version-externally-managed --compile --install-headers /Users/sudoxx2/Documents/github/delete_copy/env/include/site/python3.7/psycopg2 cwd: /private/var/folders/4d/s84v7k6d1dx_m_6qbd1wfbz80000gp/T/pip-install-cq6yuehb/psycopg2/ Complete output (48 lines): running …
- 
        Use Django ORM for Complex QueriesI'm querying a legacy Postgres database based on user input and outputting it via my django views.py file. I'd like to generate and execute the query via the Django ORM functions. The database is setup so each record utilizes a unique foreign key field nct_id that is referenced across all tables. Using the nct_id I'd like to pull desirable information from various tables of my choosing. Currently I can generate and execute the query using raw SQL. The Raw SQL I'm trying to execute via Django ORM is below: Master_Query = Studies.objects.raw(''' SELECT DISTINCT ON (Studies.nct_id) Studies.nct_id, Studies.overall_status, Eligibilities.gender, Eligibilities.criteria, Conditions.conditions_name, Facilities.city, Facilities.country, Facility_Contacts.fc_name, Facility_Contacts.email FROM Studies INNER JOIN Eligibilities on Eligibilities.nct_id = Studies.nct_id INNER JOIN Conditions on Conditions.nct_id = Studies.nct_id INNER JOIN Facilities on Facilities.nct_id = Studies.nct_id INNER JOIN Facility_Contacts on Facility_Contacts.nct_id = Studies.nct_id WHERE ((Studies.overall_status LIKE 'Recruiting' OR Studies.overall_status LIKE 'Unknown status')) AND ((Conditions.conditions_name LIKE %s OR Conditions.conditions_name LIKE %s)) AND (gender LIKE %s OR gender LIKE %s) ORDER BY nct_id LIMIT %s''', [CondTypeU, CondTypeL, GenderQuery, GenderAll, LimitQuery]) I expect to see the same output as that of my raw sql query. From the above code I should see records from all the selected columns from all the …
- 
        Django startserver not recognizing built in python libraries?I am running Python 3.7 and Django 2.1 I am using Django for the first time. I have set up a virtual environment to run my project. I have imported django into the virtual environment using pip, but when I try to issue the command python manage.py runserver I have spent many hours searching for the problem online already but can't find a solution to my problem. I have opened python to check if sqlite3 is installed and it is. I have tried to use pip install sqlite3 in the virtual environment but that doesn't work. I get the following error code Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x00000203257A1B70> Traceback (most recent call last): File "C:\Environments\django_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Environments\django_env\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Environments\django_env\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Environments\django_env\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Environments\django_env\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Environments\django_env\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Environments\django_env\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Environments\django_env\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Environments\django_env\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, …
- 
        How can i reset/remove Nginx and Gunicorn i made on AWS server ? is deleting nginx directory would reset the server?I have an AWS server when I tried deploying a Django app on it at first I messed up and made many typos so I followed The digital ocean tutorial which is so close to what I wanted to do and it worked fine. but I discovered that I needed to delete the Github repo and make a new one and I needed to use the new repo on the server so I removed the old project and cloned the new one and made a new virtual environment and referred to it in both the Gunicorn.service file and the Nginx but the app now is a total mess and returns a lot of errors and when I typed sudo journalctl -u gunicorn i found that gunicorn still refers to the old virtual environment so now I want to start from the beginning and reset everything to square 1 so how can I do that ? I don't want to wipe the machine storage as it contains other apps I want them maintained. deleting etc///gunicorn.config and etc/nginx would solve it and make me start again? btw during the whole process, I restarted both nginx and gunicorn many times but it's still …
- 
        ModuleNotFoundError: No module named 'django_heroku' , although i have correctly installed all things for it vut could not get it?I am making a django project and using css files but while deploying to heroku i got ModuleNotFoundError: No module named 'django_heroku' and i have installed all things for django-heroku...and at end it says Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 but im using css files and by disabling this applicaton error occure plz help ,,,i almost gave up im trying for 2 days HERE is the program when i do git push heroku master where error occurs remote: import django_heroku remote: ModuleNotFoundError: No module named 'django_heroku' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to fjblogs. remote: To https://git.heroku.com/fjblogs.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/fjblogs.git'
- 
        Printing well formatted sql queries in jupyter notebook with django-extensions pluginIn Django i want to see the sql in jupyter notebook in the way same way shown using ipython Eg: python manage.py shell_plus --ipython --print-sql In[1]: User.objects.all() Out[1]: SELECT "user"."id", "user"."password", "user"."last_login", "user"."is_superuser", "user"."is_staff", "user"."date_joined", "user"."first_name", "user"."last_name", "user"."email", "user"."is_active", "user"."modified_date" FROM "user" LIMIT 21 Execution time: 0.001471s [Database: default] <QuerySet [<User: yss@tst.com>]> The sql is show in a very well formated way which is very easy to understand. Now i want to try that in jupyter notebook python manage.py shell_plus --notebook --print-sql From here i followed the answer: https://stackoverflow.com/a/54632855 It says to install django_print_sql which i did then try to run from django_print_sql import print_sql with print_sql(count_only=False): q = User.objects.all() [0 queries executed, total time elapsed 0.00ms] django_print_sql: it says 0 queries and shows no sql output Also i installed sqlparser and tried the solution mentioned User.objects.all() import sqlparse from django import db sqlparse.format( db.connection.queries[-1]['sql'], reindent=True, keyword_case='upper' ) Out[1]: SELECT "user"."id",\n "user"."password",\n "user"."last_login",\n "user"."is_superuser",\n "user"."is_staff",\n "user"."date_joined",\n "user"."first_name",\n "user"."last_name",\n "user"."email",\n "user"."is_active",\n "user"."modified_date" FROM "user" LIMIT 21 The above sql does not look well formated at all. So django_print_sql and sqlparser are not giving a colorful formatted sql which is given by the python manage.py shell_plus --ipython --print-sql So how to get …
- 
        Django - edit default graphene Set queryi am building a django application with graphql and i have two models Column Model: class Column(models.Model): name = models.CharField(max_length=100) Task Model: class Task(models.Model): column = models.ForeignKey(Column, on_delete=models.CASCADE) content = models.CharField(max_length=255) position = models.IntegerField() and i have a query to query all Columns and their tasks class ColumnType(DjangoObjectType): class Meta: model = Column class Query(object): columns = graphene.List(ColumnType) def resolve_columns(self, info, **kwargs): return Column.objects.all() and i can query this by: { columns { id taskSet{ content } } } but by doing this i cant add fields to taskSet function so i want to add a filter that will get only the first 20 tasks
- 
        Programming error at all URLS in django, postgres cannot find tables in db?My Django project works fine locally on my machine, but when I deployed it to Heroku. I'm getting an error for all of my urls. My urls include: admin/ blog/ projects/ When I type in a different url, I get the following error: ProgrammingError at /blog/ relation "blog_post" does not exist LINE 1: ...t"."last_modified", "blog_post"."created_on" FROM "blog_post. This occurs at every url. Looking at the traceback, it seems like it has to do with the Templates. Here is the traceback: Template error: In template /app/personal_portfolio/templates/base.html, error at line 3 relation "blog_post" does not exist LINE 1: ...t"."last_modified", "blog_post"."created_on" FROM "blog_post... and File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute 84. return self.cursor.execute(sql, params) The above exception (relation "blog_post" does not exist LINE 1: ...t"."last_modified", "blog_post"."created_on" FROM "blog_post... ^ ) was the direct cause of the following exception: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/blog/views.py" in blog_index 12. return render(request, "blog_index.html", context) I'm also thinking it has something to do with the tables/database. I'm currently using SQLite on my local machine, but I know heroku is using postgres. I've deleted the migrations folders …
- 
        How to fix Error: pg_config executable not found on Elastic Beanstalk permanentlyI have a Django project that works with PostgreSQL on Elastic Beanstalk. I have found the next error when deploying: Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... I followed psycopg2 on elastic beanstalk - can't deploy app to solve it and it worked! BUT after a while Amazon seems to update my virtual env and the error returns so I have to go back and do the same stuff over and over again. I also have tried configuring the database instance directly from the Elastic Beanstalk panel but nothing changes. The database is on RDS and I think it's important to say that when I manually install psycopg2 on my instance and re-deploy everything works fine, I even have made a couple of deploys after that and the problems is not there but it is after a while. I really want to know how to solve it once for all. Thanks in advance.
- 
        How to use django professionally?I have just started to do web with django. In my interpretation, templates is the view showing to users, view is to handling the logic. However, I am quite confused on how to do the website better. Lets say I have a dataframe table, and I want to put it in myhtml. But at the same time, I use booststrap button to design my table, which add a button at the last of the row. So I have come up with this solution: for i in len(df.rows): #Loop 'rows' times (I know the syntax is wrong, just the algorithm) temp = df.to_html() #Convert it to string #Adding the button e.g. <td class = xxxxxxxxx> at every last of the row #Lastly #pass it to something like {xxxx|safe} to the html My question is how to do this kind of stuff in a proper way since I think this is quite stupid and hard coding. It is not efficient to convert it to string everytime.
- 
        I want my django app to get a file from a remote machineI need my django app to scp a file on a remote server into the django 'media' folder. Is spawning an scp session with pexpect in my django app the best way to go about this? Alternatively, are there libraries I can use in my django app to do this? Any help is much appreciate.
- 
        Insert data into intermediary table while submitting main modelform in DjangoI have a Task model. I want to assign task to multiple users so i have taken ManytoMany relationship. So Django is creating a ManytoMany table but i want to track that which user has completed task and when. So I took intermediary model by using through='TaskComplete'. Now I can not see task_assign_to feild in form. And even i declare in modelForms and submit it gives below error. Cannot set values on a `ManyToManyField` which specifies an intermediary model. Use audit.Membership's Manager instead. Now I want that admin selects the user from main form and into intermediary model. I tried but can not find any solution for this. below is my code. Please guide me how to do it? My Model: class Task(models.Model): task_audit_title = models.ForeignKey(MainAudit,on_delete= models.CASCADE, related_name='audit_title_for_task',verbose_name= ('Audit Title')) task_subtask_name = models.ManyToManyField(SubTask, related_name='subtask_for_task',verbose_name= ('Subtask Title')) task_subject = models.CharField(verbose_name= ('Task Subject'),max_length=100,blank=False) task_description = models.CharField(verbose_name= ('Task Description'),max_length=1000,blank=True) task_assign_to = models.ManyToManyField(User, related_name='task_assign_to', through='TaskComplete') task_assign_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name='task_crt_by') task_deadline = models.DateTimeField(null=True,blank=True) task_perticulars = models.ManyToManyField(Perticular, related_name='task_perticular', blank=True) task_created_time = models.DateTimeField(default=timezone.now) task_modified_by = models.ForeignKey(User,on_delete= models.CASCADE, related_name='task_mod_by', null=True, blank=True) task_modified_time = models.DateTimeField(null=True,blank=True) is_del = models.BooleanField(default=0) class Meta: permissions = ( ("change_temp_delete_task", "Can delete temporarily"), ) def __str__(self): return self.task_subject def get_absolute_url(self): return reverse('create-task') class TaskComplete(models.Model): …
- 
        Django Overwrite storage not working correctlyI have a model that looks like this: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=160, null=True) avatar = models.ImageField(storage=OverwriteStorage(), upload_to=create_user_image_path) if self.avatar: with Image.open(self.avatar) as image: image_path = self.avatar.path image_name = self.avatar.path[:-4] image_ext = self.avatar.path[-4:] resize_images(image, image_path, image_name, image_ext) image.close() Each time a user uploads a picture, I overwrite the storage here: class OverwriteStorage(FileSystemStorage): def get_available_name(self, name, *args, **kwargs): try: file_path = os.path.dirname(name) shutil.rmtree(os.path.join(settings.MEDIA_ROOT, file_path)) except FileNotFoundError: pass return name So basically, because I create a random image name (needed so that browser updates cache), I need to delete the entire files in the directory. This works perfectly, however, after uploading once again after a few seconds I get the following error: PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\Users\xx\xx\xx\media\users\179\avatars \179312.jpg' I see inside FileSystemStorage there's this comment: # There's a potential race condition between get_available_name and # saving the file; it's possible that two threads might return the # same name, at which point all sorts of fun happens. So we need to # try to create the file, but if it already exists we have to go back # to get_available_name() and try again. How do …
- 
        Why Django requires "_id" in the name of ForeignKey field?I have models for players, teams and matches. Obviously, that I have some ForeignKey field. But if I don't add "_id" in the end of ForeignKey field, Django raises the error: "no such column: betbot_testmatch.leftTeam_id" I have tried to add "_id" in the end of my ForeignKey fields and it really solved the problem, but in my previous project I designed, I have been usin FK fields without any "_id" in the end of field names and there were no problems. models.py from django.db import models class TestMatch(models.Model): leftTeam = models.ForeignKey('TestTeam', on_delete=models.DO_NOTHING, related_name='+', default='Left Team') rightTeam = models.ForeignKey('TestTeam', on_delete=models.DO_NOTHING, related_name='+', default='Right Team') class TestTeam(models.Model): name = models.CharField(max_length=30, default='Team') urlslug = models.SlugField(max_length=5) class TestPlayer(models.Model): name = models.CharField(max_length=100, default='Player') nick = models.CharField(max_length=20, default='Nickname') team_id = models.ForeignKey('TestTeam', on_delete=models.DO_NOTHING, default='Team') #photo = models.ImageField(upload_to='', null=True) No = 'N' Yes = 'Y' STANDIN_CHOICES = [ (Yes, 'Yes'), (No, 'No'), ] standin = models.CharField(max_length=5, choices=STANDIN_CHOICES, default=No) slug = models.SlugField(max_length=20, default=nick) I want that I could use my names for ForeignKey field without the mistake.
- 
        Cannot Edit User on django adminI try to make second user that contain 'staff' and 'super user' in django admin built in. The result was The cannot saved it self. Then I try to edit my user account through this django admin panel, and it cannot work to. The sistem pop up a message that i have missing some form to edit, but it didn't appear. I don't know what i must do to solve this issue my user model: from django.contrib.auth.models import AbstractUser from django.db.models import CharField from django.urls import reverse from django.utils.translation import ugettext_lazy as _ class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = CharField(_("Name of User"), blank=True, max_length=255) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) form: from django.contrib.auth import get_user_model, forms from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from snowpenguin.django.recaptcha2.fields import ReCaptchaField from snowpenguin.django.recaptcha2.widgets import ReCaptchaWidget User = get_user_model() class UserChangeForm(forms.UserChangeForm): captcha = ReCaptchaField(widget=ReCaptchaWidget()) class Meta(forms.UserChangeForm.Meta): model = User class UserCreationForm(forms.UserCreationForm): error_message = forms.UserCreationForm.error_messages.update( {"duplicate_username": _("This username has already been taken.")} ) class Meta(forms.UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise ValidationError(self.error_messages["duplicate_username"]) user admin: from django.contrib import admin from django.contrib.auth import …
- 
        How can I generate a multi-step process in Django without changing pages (w/out a new request)?I have a model (Category) which references itself for its parent category. The categorty's roots can be found with a filter and aggregated into a select dropdown for example. But how would you generate another dropdown with the selected categories sub-category? As far as I can tell, the solution would be to use Django REST api, but it seems like a bit of an overkill just to select a category. Would anyone have any suggestions? My model is: class Category(models.Model): # PK cat_id = models.IntegerField(primary_key=True) # Foreign parent_category = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) # Column name = models.CharField(max_length=128) # the name of the category limit_message = models.CharField(max_length=255, null=True, blank=True) level = models.PositiveIntegerField() # 1 for root (major category) followed by 2, 3 ... is_leaf = models.BooleanField() is_enabled = models.BooleanField(default=True) def __str__(self): return self.name
- 
        How to include the routes of React to django?I am working on a varsity project which is a web based application.It uses React as frontend and django as backend. Here is my app.js.. function App() { return ( <BrowserRouter> <Route path="signin/" exact component={Signin} /> <Route path="signin/signup/" component={SignUp} /> </BrowserRouter> ); } my django base urls looks like.. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^dream11/', include('core.urls')), url(r'^api/', include('api.urls')), url(r'^api-token-auth/$', views.obtain_auth_token, name="token" ) ] when i'm going to dream11/signin/ link , django is not showing anything.it gives me the error, Using the URLconf defined in Dream11v3.urls, Django tried these URL patterns, in this order: ^admin/ ^dream11/ ^$ [name='index'] ^api/ ^api-token-auth/$ [name='token'] The current path, dream11/signin/, didn't match any of these. How can I solve this?
- 
        Django 2.2 staticfiles do not work in developmentI'm making a new django app where a user can upload images and then they can be displayed on a page. I've read the django docs 10000 times through and I still don't understand why my images aren't loading (DEBUG = True) All my images are going to where they're supposed to be and in the admin in my models django has the right path that leads to the image but it just won't load properly. my setup in settings.py: STATIC_URL = '/static/' STATIC_ROOT = 'static' # live cdn such as AWS S3 STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(STATIC_ROOT, 'media') MEDIA_URL = '/img/' my directories: |- src |- myproject |- settings.py, views.py, urls.py etc |- myapp |- views.py urls.py models.py forms.py etc |- static (this folder is empty and appeared after running collectstatic |- templates |- db.sqlite3 |- manage.py |- static (this folder is OUTSIDE src) |- admin |- django admin stuff |- media |- img |- myimage.png in models.py of myapp the imagefield upload_to = 'img/' as i said, the images don't load on the page but to upload to static/media/img/image_name.png I've been trying to fix this for ages but i can't get any help from …