Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
can I filter against the URL with a Django Rest Framework ViewSet?
Is there a way to filter against the URL (as described here) using a DRF ViewSet? I have the following sort of code: models.py: class Author(models.Model): name = models.CharField() class Book(models.Model): title = models.CharField() author = models.ForeignKey(Author, related_name="books") views.py: class BookViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = BookSerializer def get_queryset(self): author = self.kwargs["author"] return Book.objects.filter(author__name=author) urls.py: api_router = SimpleRouter() api_router.register(r"books/<str:author>", BookViewSet) urlpatterns = [ path("", include(api_router.urls)) ] But this pattern actually matches the URL /books/<str:author> (with the angle brackets) instead of letting my enter something like /books/shakespeare and get back all books with the author "shakespeare". Is it possible to do this kind of a filter with a ViewSet? -
Can I avoid the need for authentication when testing Django Rest Framework
I am trying to use DRF testing for the first time, so I created the following TestCase: class TestInventoryActionInputNoSeriable(TestCase): def setUp(self): self.repository = create_repository() self.not_seriable_product = create_not_seriable_product() def test_post_inventory_input_not_seriable(self): client = APIClient() response = client.post('/api/inventory/execute_action/', { 'action': 'input', 'repository': self.repository.id, 'product': self.not_seriable_product.id, 'amount': 1, }) self.assertEqual(response.status_code, 200) inventory_actions = models.InventoryAction.objects.all() inventory_inputs = models.InventoryInput.objects.all() kardexs = models.Kardex.objects.all() self.assertEqual(len(inventory_actions), 1) self.assertEqual(len(inventory_inputs), 1) self.assertEqual(len(kardexs), 1) inventory_action = inventory_actions.first() inventory_input = inventory_inputs.first() kardex = kardexs.first() self.assertEqual(inventory_action.action_content_type.model, 'inventoryinput') self.assertEqual(inventory_action.action_object_id, inventory_input.id) self.assertEqual(kardex.type, models.KARDEX_INPUT) self.assertEqual(kardex.repository_id, self.repository_id) self.assertEqual(kardex.product_id, self.not_seriable_product.id) self.assertEqual(kardex.amount, 1) self.assertEqual(kardex.stock, 1) But I get the following result: (TCDigitalVenv) MacBook-Pro-de-Hugo:TCDigital hugovillalobos$ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_post_inventory_input_not_seriable (inventory.tests.TestInventoryActionInputNoSeriable) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/TCDigitalProject/TCDigitalBackend/TCDigital/inventory/tests.py", line 31, in test_post_inventory_input_not_seriable self.assertEqual(response.status_code, 200) AssertionError: 401 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.083s FAILED (failures=1) Destroying test database for alias 'default'... Which means that the request was rejected because of authentication failure. I followed DRF authentication documentation: def test_post_inventory_input_not_seriable(self): token = Token.objects.get(user__username='admin') client = APIClient() client.credentials(HTTP_AUTHORIZATION='token '+token.key) response = client.post('/api/inventory/execute_action/', { 'action': 'input', 'repository': self.repository.id, 'product': self.not_seriable_product.id, 'amount': 1, }) self.assertEqual(response.status_code, 200) ... But I get this error: (TCDigitalVenv) MacBook-Pro-de-Hugo:TCDigital hugovillalobos$ python manage.py test … -
Django : ForeignKey data insertion issue (can't add product
I'm new to django My problem is, in django-admin-interface whenever I try to create a product with a category, that is already occupied by another existing product, I get an error : Product with this Category already exists in admin-UI for example : I have created 1 product i-phone with category electronic , It saves into DB. Now if I create another product Google-nexus with same category i.e. electronic, I can't create the product because of this error is shown in django-admin-interface : Product with this Category already exists I created 3 models in my app like below models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Product(models.Model): product_name = models.CharField(max_length=255) tags = models.ManyToManyField(Tag) image = models.ImageField(upload_to='images') category = models.OneToOneField(Category, on_delete=models.CASCADE) description = models.TextField() def __str__(self): return self.product_name forms.py from django import forms from.models import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = ('product_name', 'category', 'description', 'image', 'tags') def __init__(self,*args,**kwargs): super(ProductForm,self).__init__(*args,**kwargs) self.fields['category'].empty_label = 'Select' self.fields['image'].required = False Do I have wrong model relationship.? error snapshot of django-admin -
The current project's Python requirement (^2.7) is not compatible with some of the required packages Python requirement
I keep receiving this error when I run poetry add django confidential Using version ^3.0.4 for django Using version ^2.3.0 for confidential Updating dependencies Resolving dependencies... (0.0s) [SolverProblemError] The current project's Python requirement (^2.7) is not compatible with some of the required packages Python requirement: - django requires Python >=3.6 Because no versions of django match >3.0.4,<4.0.0 and django (3.0.4) requires Python >=3.6, django is forbidden. So, because pythontest depends on django (^3.0.4), version solving failed. When I check my python version I see 3.8.2 and my Django version is 3.0.4 so I'm not sure what else the issue could be. -
NoReverseMatch - I am creating a sample crm
This is my error: Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$'] My codes are here: from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name='products'), path('customer/<str:pk_test>/', views.customer, name="customer"), path('create_order/<str:pk>/', views.createOrder, name="create_order"), path('update_order/<str:pk>/', views.updateOrder, name="update_order"), path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"), ] def createOrder(request, pk): OrderFormSet = inlineformset_factory(Customer, Order, fields=('product','status'), extra=10) # form = OrderForm() customer = Customer.objects.get(id=pk) formset = OrderFormSet(queryset=Order.objects.none(),instance=customer) # form = OrderForm(initial={'customer':customer}) if request.method == 'POST': # print('Printing POST', request.POST) # form = OrderForm(request.POST) formset = OrderFormSet(request.POST, instance=customer) if formset.is_valid(): formset.save() # return HttpResponse('<h1>Congratulations</h1> <a href="/">Please return to home<a/>') return redirect('/') context = {'formset':formset } return render(request, 'accounts/order_form.html', context) Where am I doing wrong? Please help me. -
Could not find a version that satisfies the requirement pywin32==227 heroku
I am having this issue with heroku. i am trying to push my application to heroku but it seems that heroku can not install pywin32=227 but i do not know why is this happening. i hope that someone can help me whit this issue. Requirements.txt: appdirs==1.4.3 asgiref==3.2.3 awsebcli==3.17.1 botocore==1.14.17 cement==2.8.2 certifi==2019.11.28 chardet==3.0.4 colorama==0.3.9 distlib==0.3.0 dj-database-url==0.5.0 Django==2.1.15 django-pyodbc-azure==2.1.0.0 docutils==0.15.2 filelock==3.0.12 future==0.16.0 gunicorn==20.0.4 idna==2.7 importlib-metadata==1.5.0 jmespath==0.9.5 pathspec==0.5.9 Pillow==7.0.0 psycopg2==2.8.4 pyodbc==4.0.30 pypiwin32==223 python-dateutil==2.8.0 python-decouple==3.3 pytz==2019.3 pywin32==227 PyYAML==5.2 requests==2.20.1 semantic-version==2.5.0 six==1.11.0 sqlparse==0.3.1 stripe==2.43.0 termcolor==1.1.0 urllib3==1.24.3 virtualenv==20.0.7 wcwidth==0.1.8 whitenoise==5.0.1 zipp==3.1.0 I'm developing on Windows 10 Professional, and the application works fine there: C:\Users\GuGarza\test>git push heroku master Enumerating objects: 363, done. Counting objects: 100% (363/363), done. Delta compression using up to 4 threads Compressing objects: 100% (348/348), done. Writing objects: 100% (363/363), 257.21 KiB | 1.42 MiB/s, done. Total 363 (delta 107), reused 0 (delta 0) remote: Downloading pytz-2019.3-py2.py3-none-any.whl (509 kB) remote: ERROR: Could not find a version that satisfies the requirement pywin32==227 (from -r /tmp/build_000de559e8272ea11b28b5ee568bf649/requirements.txt (line 28)) (from versions: none) remote: ERROR: No matching distribution found for pywin32==227 (from -r /tmp/build_000de559e8272ea11b28b5ee568bf649/requirements.txt (line 28)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected … -
One View Saving Objects to Two Models Django
I have a view that will save the data from its form to one model 'PackingLists', but the same view also creates a pdf which should create a new object and be saved into a separate model 'PackingListDocuments'. Saving the form and updating the 'PackingLists' model is no issue, creating the document is no issue, but how to automatically create a new object in PackingListDocuments I am not sure. models.py class PackingList(models.Model): Reference_Number = models.CharField(max_length=100, null=True) ... class PackingListDocuments(models.Model): Reference_Number = models.ForeignKey(PackingList) PackingListDocument = models.FileField(upload_to='media') views.py def PackingListView(request): if request.method == "POST": form = PackingListForm(request.POST) if form.is_valid(): ... elif 'save' in request.POST: context = request.session['data'] = form.cleaned_data pdf = render_to_pdf('packlist_preview.html', context) filename = "YourPDF_Order{}.pdf" PackingListDocuments.PackingListDocument.save(filename, File(BytesIO(pdf.content))) #this does not work form.save() messages.success(request, "Success: Packing List Has Been Created!") return redirect('HomeView') else: form = PackingListForm() return render(request, 'packlist.html', {'form': form}) -
Django REST: Serialize a ManytoMany field that is within another ManytoMany field
I have a three models with Opportunity being the Serialized model. The Broker model is a M2M field within the Project field. Then the ServiceLines model is a M2M field of Broker model. When I serialize my data, I receive all information about the Broker model related to the Opportunity, however, I do not receive any information on the ServiceLine within the Broker M2M. The following are my Serializers: class ServiceLineSerializer(serializers.ModelSerializer): class Meta: model = ServiceLine fields = ['id', 'servicelinename'] depth = 1 class BrokerSerializer(serializers.ModelSerializer): class Meta: model = Broker fields = ['id', 'fullname', 'primarybl'] depth = 1 primarybl = ServiceLineSerializer(many=True) class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Opportunity fields = [*] depth = 1 broker = BrokerSerializer(many=True) And my models: class Broker(models.Model): firstname = models.CharField(max_length=100, default= "First Name") lastname = models.CharField(max_length=100, default= "Last Name") fullname = models.CharField(max_length=100, default= "Full Name") primarybl = models.ManyToManyField('ServiceLine') class ServiceLine(models.Model): servicelinename = models.CharField(max_length=100) def __str__(self): return self.servicelinename class Opportunity(models.Model): broker = models.ManyToManyField('team.Broker') Thanks for your time! -
Refreshing request in Django
I'm pretty new to Django and I'm trying to build a website, which finds a movie for you. My problem is that sometimes API doesn't find anything and I'm getting error "query must be provided". I'd like to know if there is any way to refresh the request until query is provided? here is my code view def result(req): search_result = req.GET.get('search') movie_genre = req.GET.get('movie_genre') if search_result == '' and movie_genre == 'none': return redirect('/') else: result = search_movie(search_result) if result == None: return redirect('/') else: movie_title = result[0] movie_id = result[1] movie_release_date = result[2] movie_overview = result[3] number_of_movies = result[4] return render(req, 'movie_app/result.html', { 'movie_title': movie_title, 'movie_id': movie_id, 'movie_release_date': movie_release_date, 'movie_overview': movie_overview, 'number_of_movies': number_of_movies, }) Here especially is where I need help: if result == None: return redirect('/') From UX point it seems dumb to redirect to homepage. I'be really thankful for help! -
Unable to import django-rq into my Django project
I'm experiencing problems importing Django-rq in my project, I suspect that I am perhaps missing something really silly/obvious but I can't for the like of me figure it out. In the 'view.py' file of my pages app, I have attempted to import django_rq but I am getting a red squiggly line underneath it in visual studio and it doesn't seem to be working at all. from django.shortcuts import render from django.views.generic import TemplateView import time import django_rq def delayfunc(): time.sleep(30) return True class HomePageView(TemplateView): template_name = 'home.html' Can anyone see what the issue is? Here is my repository: https://github.com/davidfoxgit/django-rq-example/tree/master Thanks -
Interstitial Page / Intermediare Page before external Link - Django
I'm developing a price compare shopping website and i'm trying to figured out how can I achieve the following behavior: I have a Product Model and each product has-many Offers. Each offer has the company name and a external link to the product checkout page. I'd like when people click on the external link to the checkout actually reachs another page, let's say "http://mywebsite.com/redirect.html" which contains the following: You'll be redirected to the checkout page in 5 seconds. After the 5 seconds redirect them to the checkout page. How can I achieve that? Anybody has some reference to recommends me? -
Django channels Error when starting the server
I have my channels placed in the top of INSTALLED_APPS. When I ty to start the server I get following error: File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 224, in fetch_command klass = load_command_class(app_name, subcommand) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 36, in load_command_class module = import_module('%s.management.commands.%s' % (app_name, name)) File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\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 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\management\commands\runserver.py", line 10, in <module> from channels import __version__ ImportError: cannot import name '__version__' from 'channels' (C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\channels\__init__.py)``` -
django path using wsgi apache loses first parameter
I have a Django set up to handle requests for http://myserver/bayeux/online as follows: in the apache http.conf file: this line WSGIScriptAlias /bayeux /home/peter/path_to_wsgi In the top-level urls.py file: if I have this line urlpatterns = [ path('bayeux', _call_to_view)] The pattern will not match. This is because the first path element "bayeux" is used to direct to the urls.py structure, and so is not visible to the path calls inside urls.py. So instead, I have to have this line in urls.py: urlpatterns = [ path('online', _call_to_view)] The problem with this is that I have other folders I want to send calls to django. For http://myserver/anotherbook/online, the urls.py file ONLY sees the 'online' part of the path. There is no way to have different handlers for /bayeux and /anotherbook. Both will be handled by the same _call_to_view function. Of course, I can examine the whole url within call_to_view, but that is ugly. An alternative would be to have EVERY call on the server routed to django by having this in my httpd.conf: WSGIScriptAlias / /home/peter/path_to_wsgi With this set up I could have the lines urlpatterns = [ path('bayeux', _call_to_view)] urlpatterns = [ path('anotherbook', _call_to_different_view)] But this has a dire side-effect. It means … -
Django Inheritance gives import errors
I have one class (DeckDeviceUtil) with an abstract function (get_active_deckdevices) who needs to be inherited by 2 classes (Deck and Device). The structure is as follows: A.py from models import Deck class DeckDeviceUtil: @property @abstractmethod def deckdevice(self): pass def get_active_deckdevices(self): #somecode class Device(models.Model, DeckDeviceUtil): #somecode B.py from backend.devices.models import DeckDeviceUtil class Deck(models.Model, DeckDeviceUtil): #somecode I get following error: from backend.house.models import Deck ImportError: cannot import name 'Deck' probably because the 2 python files/classes need each other. When I try to do the imports inside the classes there are other errors when import DeckDeviceUtil inside Deck : class Deck(models.Model, DeckDeviceUtil): NameError: name 'DeckDeviceUtil' is not defined when import Deck inside Device: from backend.house.models import Deck ImportError: cannot import name 'Deck' Important: Device needs to import Deck What's the best way to solve this? -
How to handle POST form data with Django (refresh avoided)?
I'm trying to save the form's data in a database using Django. Refreshing after click on submit button is avoided using: scripts.py var form = document.getElementById("mail_form_id"); function handleForm(event) { event.preventDefault(); } form.addEventListener('submit', handleForm); function send_mailform(){ console.log("cal") var http = new XMLHttpRequest(); http.open("POST", "", true); http.setRequestHeader("Content-type","application/x-www-form-urlencoded"); var params = "search=" + document.getElementById('mail_input').value; http.send(params); http.onload = function() { alert(http.responseText); } } document.getElementById("mail_send_btn").addEventListener('click', send_mailform, false); views.py #Mail check if request.POST: Marketingform = Marketingforms(request.POST) print("sdf") if Marketingform.is_valid(): receiver_mail = Marketingform.cleaned_data['receiver_mail'] p = mail_receiver(receiver_mail=receiver_mail) p.save() print("correct") route_n_valid = False template ='index.html' views.py class mailForm(forms.ModelForm): class Meta: model = mail_receiver fields =[ 'receiver_mail', ] widgets = { 'receiver_mail': forms.EmailInput(attrs={ 'id':'mail_input', 'name':'mail_input'}), } How can I receive the value of params in the django views.py? -
Celery not connecting to Redis
I'm working in a Django project and i'm trying to integrate celery into my project but my app doesn't seem to be able to connect to my redis-server that I'm running locally. This is what it shows me when I run celery -A project worker. ---- **** ----- --- * *** * -- Linux-4.15.0-58-generic-x86_64-with-Ubuntu-18.04-bionic 2020-03-18 19:06:29 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: proyecto_is2:0x7f7c98351518 - ** ---------- .> transport: redis://h:**@ec2-34-202-114-79.compute-1.amazonaws.com:17729// - ** ---------- .> results: redis://127.0.0.1:6379/0 - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [2020-03-18 19:31:24,595: ERROR/MainProcess] consumer: Cannot connect to redis://h:**@ec2-34-202-114-79.compute-1.amazonaws.com:17729//: Error 110 connecting to ec2-34-202-114-79.compute-1.amazonaws.com:17729. Connection timed out.. I noticed that the url in transport is not my localhost and I don't know where that got set up. I'm using celery 4.3.0, redis 3.2.1. In my celery.py I have import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proyecto_is2.settings.dev_settings') app = Celery('proyecto_is2') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() In my settings i have ... other configs CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' -
How can i render objects in html through django templating via primary key?
i have a problem in searching articles on my home page. the problem is that when i enter a query in a search bar , the error "Reverse for 'blog_detail/' not found. 'blog_detail/' is not a valid view function or pattern name." appears. code homepage from where i search a query <form method="get" action={% url 'search' %} class=""> <!-- <form method="get" action="{% url 'search' %} class="">--> <input type="text" name="search" class="form-control bg-dark text-white" placeholder="Search Articles" aria-label="Recipient's username" aria-describedby="basic-addon2"> <div class="input-group-append bg-dark"> <button class="btn btn-outline-primary bg-danger text-white" type="submit" >Search </button> </div> </form> search.html The action of the form sends query to this page <div class="row"> {% for item in post %} <div class="card my-3 text-white bg-dark mb-3" style="width: 18rem;"> <img src="/media/{{item.thumbnail}}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{item.title}}</h5> <p class="card-text">{{item.intro}}</p> <a href="{% url 'blog_detail/' id=item.post_id %}" class="btn btn-primary">read more...</a> </div> </div> {% if forloop.counter|divisibleby:5 %} </div> {% endif %} {% endfor %} </div> this (href="{% url 'blog_detail/' id=item.post_id %}") is giving an error saying (NoReverseMatch at /search/) in the urls.py the route for blog_detail is : path("blog_detail/<int:id>", views.blog_detail, name = "blog"), and for search route is : path("search/", views.search, name="search"), in the models the primary key is set as post_id : post_id = … -
Django: Unable to configure handler 'logging.handlers.SysLogHandler'
Receiving this error when running Django app. "ValueError: Unable to configure handler 'logging.handlers.SysLogHandler'" On Windows 10, I think I gave the folder dev/log full access for my user. Log handlers: #Loggly settings LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'django': { 'format':'django: %(message)s', }, }, 'handlers': { 'logging.handlers.SysLogHandler': { 'level': 'DEBUG', 'class': 'logging.handlers.SysLogHandler', 'facility': 'local7', 'formatter': 'django', 'address' : '/dev/log', }, }, 'loggers': { 'loggly_logs':{ 'handlers': ['logging.handlers.SysLogHandler'], 'propagate': True, 'format':'django: %(message)s', 'level': 'DEBUG', }, } } -
Django import messes up Celery
I have a django project with the following Django project structure: project/ ... some_app/ __init__.py some_module_where_i_import_some_utils.py server/ __init__.py settings/ __init__.py common.py dev.py ... celery.py ... utils/ __init__.py some_utils.py manage.py ... When using utils I import them the following way: from project.utils.some_utils import whatever And it works well. However when I run celery worker using DJANGO_SETTINGS_MODULE=server.settings.dev celery -A server worker --beat -l info autodiscover_tasks fails with the following error ModuleNotFoundError: No module named 'project'. Here are contents of server/celery.py: import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings.prod") app = Celery("server") app.config_from_object("django.conf:settings", namespace="CELERY") # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) Here is server/__init__.py: from .celery import app as celery_app __all__ = ("celery_app",) -
Django - user profile picture not being displayed in the browser
In my project, I have a DetailView, so a user can view their profile. On here, I want to display their profile picture. However when I open the browser and go to the detail page, no profile picture is displayed. My code is displayed below. views.py: class DetailProfile(generic.DetailView): model = User # Template that a users profile picture should be displayed in template_name = 'detail_profile.html' detail_profile.html: <img width="200px" src="{{ user.profilePic.url }}" alt=""> Error returned by the browser: GET http://localhost:8000/media/static/default-profile.png 404 (Not Found) urls.py (for the users apps): urlpatterns = [ path('signup/', views.signup, name='signup'), path('login/', views.login, name='login'), path('resetone/', views.resetone, name='resetone'), path('resetwo/', views.resetwo, name='resetwo'), path('viewprofile/<int:pk>', views.DetailProfile.as_view(), name='detail_profile'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) SETTINGS.PY: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'proj2/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' Currently, all the users have the file default-profile.png assigned to their profile pic, however later I am going to implement the ability for users to change their profile pic. default-profile.png is stored in the static folder(Check my settings.py code above). Does anybody know why this file isn't being displayed in the browser and why I am getting returned the error displayed above? Thank you. -
I am using django with mongodb, I need to export databases from the website
I was looking for how to do that but I just want a button that lets me download a csv and the same that lets me import a scv (or alike) and just sets the current database to that one. Is there a short way around for that? -
How exactly to use `current_app` and `urlconf` arguments of the `reverse()` function in Django
I had to use the reverse() function in my project and saw usage of the reverse() in other projects, but i have never used current_app and urlconf arguments. As i read in docs: The current_app argument allows you to provide a hint to the resolver indicating the application to which the currently executing view belongs. This current_app argument is used as a hint to resolve application namespaces into URLs on specific application instances, according to the namespaced URL resolution strategy. The urlconf argument is the URLconf module containing the URL patterns to use for reversing. By default, the root URLconf for the current thread is used. And i never saw examples of their usage. Could you give me some tips or maybe a little usage example, please, to understand how should i use them properly? -
How to use update_or_create when updating values in Django database from CSV files
Problem summary: I don't understand the syntax for objects.update_or_create in Django. CSV files have the field names in first row: # data.csv field1, field2, 12, 14, 35, 56, I have a model for my postgresql database in models.py: from django.db import models # example model, real one has 100 fields of different types class MyModel(models.Model): field1 = models.IntegerField(blank=True, null=True) field2 = models.IntegerField(blank=True, null=True) Now I want to create/update the database when new data comes in in form of CSV files: import csv with open('./datafiles/data.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: update, created = MyModel.objects.update_or_create( defaults={???}, ??? ) update.save() What goes into the question mark marked places? -
Unable to run Django code on localhost, using pythonanywhere's bash console
I installed Django and started a project. The moment I made the project, I ran python manage.py runserver on pythonanywhere's bash console. It gave the output Starting development server at http://127.0.0.1:8000/ However when I opened the URL, it showed me "This site can't be reached" (venv) 18:31 ~/django_sample $ python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). You have 17 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. March 18, 2020 - 18:35:54 Django version 3.0.4, using settings 'django_sample.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Error: That port is already in use. (venv) 18:35 ~/django_sample $ -
Where and how put my business logic in django
A friend recommended that I read the book two scoops Django and I was amazed at the recommendations he makes for a robust and well-designed Django project. This reading created a doubt in me and it is where I put the business logic, I give an example. Suppose I have two models: models.py class Sparks(models.Model): flavor = models.CharField(max_length=100) quantity = models.IntegerField(default=0) class Frozen(models.Model): flavor = models.CharField(max_length=100) has_cone = models.BooleanField() quantity_sparks = models.IntegerField(default=0) Let's suppose that every time I add a frozen, if it has sparks, I have to subtract it from the Sparks model and check that there is an available quantity. In the book they recommend putting this logic in models.py or forms.py. Where and how should I put this?