Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django NoReverseMatch Error - Reverse for 'edit_post' with arguments '('',)' not found
The Problem I'm making a project, where you can make new blog posts and edit existing blog posts. I have a problem with editing existing posts; I get a "NoReverseMatch" Exception, when I go to the main localhost:8000 page. It keeps highlighting the tag {% url 'blogs:edit_posts' post.id %} in index.html. I think I'm missing something, but I just can't find out what it is. The traceback is like this: Exception Type: NoReverseMatch at / Exception Value: Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_post/(?P<post_id>\\d+)/$'] What i've tried I've tried to pass the post.id directly in the context dictionary in the view edit_posts. I've tried passing the post.id to the index function in views.py. I've tried renaming some of the variables to avoid potential naming conflicts. My Code My models.py looks like this: from django.db import models class BlogPost(models.Model): """A blogpost on the Home Page.""" title = models.CharField(max_length=300) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.title My views.py looks like this: from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from .models import BlogPost from .forms import BlogPostForm def index(request): """The Home Page for … -
What I am doing wrong by allowing user to download file from AWS with django boto3?
New to StackOverflow, I will try to be clear with my question. All of my media files are uploaded to AWS, I created a view that allows each user to download images. Before, I did it without the boto that summed up this back-end doesn't support absolute path. And now, after some research, I'm using the s3 boto3 connection. Here is my model class Photo(models.Model): file = models.ImageField(upload_to="uploaded_documents/") total_download = models.PositiveIntegerField() the view is: def download_file(request,id): photo = get_object_or_404(Photo,id=id) photo.total_download += 1 photo.save() path = os.path.basename(photo.file.name) # path = '/media/public/uploaded_documents/museum.jpg' client = boto3.client('s3',aws_access_key_id=settings.AWS_ACCESS_KEY_ID, aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY) resource = boto3.resource('s3') bucket = resource.Bucket(settings.AWS_STORAGE_BUCKET_NAME) bucket.download_file(path, 'my_local_image.jpg') Here I don't know what to do to trigger it. when I run it, I get the following error: NoCredentialsError at /api/download-file/75 Exception Type: NoCredentialsError Exception Value: Unable to locate credentials -
How to stop web-app from refreshing every time WIFI reconnects
I am relatively (1 year) new to web app development and I currently have an Angular 5 front end and Django back-end app. Every time I am on a tablet or smartphone and the wifi reconnects (goes from one router to another) or I switch the wifi off and back on again immediately, my app reloads by itself. Does not matter if it's Chrome or Firefox. The thing is, I have opened other websites as well in a few tabs, and when I switch my wifi off and on again, ONLY MY APP refreshes. This is extremely frustrating cause I loose any information that was being entered in a form. (And some forms may be long) The fact that it is only my app reloading when the wifi comes back on, makes me think that I have some settings somewhere that other sites do not have. But I do not even know where to begin to look. I have look everywhere on the internet for anything for 2 days now but have not found an answer. -
Another Grab Object in Django Query
I am again struggling with retrieving what I need from my database. This is still for a pretty basic library-style app in Django. I am still very new to Django - this is my first real full project. At any rate, in models, I set up the following Review table: class Review(models.Model): star_rating = models.IntegerField() comments = models.TextField() book = models.ForeignKey("Book", on_delete=models.CASCADE, related_name="reviews") created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name="reviews_added") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = ReviewManager() Then in views, I have a route for books/home/ where I want to be able to display information for the current user (this part is done and works well) and also for that current user's reviews. Here is my books_home method, currently. I believe I am close but I am not sure how to grab the Review objects. Unless I'm mistaken, I just need to replace the two instances of "???" below with real code. Your help is much appreciated. def books_home(request): if request.method == "GET": first_name = User.objects.get(id=request.session['uid']).first_name last_name = User.objects.get(id=request.session['uid']).last_name email = User.objects.get(id=request.session['uid']).email review_comments = User.objects.get(id=???).comments review_rating = User.objects.get(id=???).star_rating context = { 'first_name' : first_name, 'email' : email, 'last_name' : last_name, 'review_comments' : review_comments, 'review_rating' : review_rating } return render(request, 'html_files/home.html', … -
Display Static file Django and rest-framework
I need to Display the static file, I follow Django document but it is not displayed. 1.In Models file image = models.ImageField(upload_to='images/') 2.In urls.py file from django.conf import settings from django.conf.urls.static import static ... + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) 3.In settings.py file STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'lost_items/static/') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' finally, I run this command python manage.py collectstatic when I GET API, the image in this URL "image": "http://localhost:8000/media/images/n73.jpg" So, When I click on it, I get the page not found, and: The current path, media/images/money.jpg, didn't match any of these. -
Is it possible to use Django's admin portal when using a graph database?
Is there any way I can use the django's admin portal? At least reuse the UI rendering? I'll be using Django + graph database for my application. So my models will not be extending django.db.models.Model. Instead it'll be extending a Node class provided by graph DB's library. The application also uses JWT based authentication (with a custom JWT middleware). -
Inherited forms don't see new fields
My problem is that self.cleaned_data in an inherited form doesn't contain new fields, just fields from a base form. The base form: class BaseDealForm(forms.Form): ... transport = forms.ChoiceField(choices=( ('A', 'auto'), ('R', 'railways'), ) city = forms.CharField(required=False) ... def __init__(self, request, *args, **kwargs): self.request = request super(BaseDealForm, self).__init__(*args, **kwargs) ... The inherited form: class ScrapMetalDealForm(BaseDealForm): amount = forms.IntegerField(min_value=20) opportunity_to_deliver = forms.BooleanField(required=False) ... def clean(self): cleaned_data = super(ScrapMetalDealForm, self).clean() // Here it has amount and opporunity_to_deliver fields. if cleaned_data.get('transport'): if not cleaned_data.get('opportunity_to_deliver') and \ not cleaned_data.get('city'): raise forms.ValidationError('Укажите город.') return cleaned_data def clean_amount(self): value = self.cleaned_data.get('amount') // However here it doesn't have them, so that it always return None. ... return value ... When I've copied fields from the base form to inherited form and just inherited it from forms.Form everything was ok. -
Problems when calling self.full_clean() in model save()
We are using Django (currently 1.11.15) for Speedy Net and Speedy Match. Recently I found out that django.db.models.Model save() method doesn't call full_clean(). I read about it a little (for example on Why doesn't django's model.save() call full_clean()?) and decided it's a better programming practice to call self.full_clean() before saving the model. I implemented it with class ValidateModelMixin (from Django model mixin to force Django to validate (i.e. call full_clean) before save): class ValidateModelMixin(object): def save(self, *args, **kwargs): """Call `full_clean` before saving.""" self.full_clean() return super().save(*args, **kwargs) And then inherit from it in my base model class (which all models inherit from): class BaseModel(ValidateModelMixin, models.Model): But the problem is, most of my tests fail with this message: ====================================================================== ERROR: test_user_gets_redirected_to_his_profile (speedy.net.accounts.tests.test_views.IndexViewTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "speedy\net\accounts\tests\test_views.py", line 8, in setUp self.user = ActiveUserFactory() File "VENV~1\lib\site-packages\factory\base.py", line 46, in __call__ return cls.create(**kwargs) File "VENV~1\lib\site-packages\factory\base.py", line 563, in create return cls._generate(enums.CREATE_STRATEGY, kwargs) File "VENV~1\lib\site-packages\factory\base.py", line 500, in _generate return step.build() File "VENV~1\lib\site-packages\factory\builder.py", line 279, in build kwargs=kwargs, File "VENV~1\lib\site-packages\factory\base.py", line 314, in instantiate return self.factory._create(model, *args, **kwargs) File "VENV~1\lib\site-packages\factory\django.py", line 165, in _create return manager.create(*args, **kwargs) File "VENV~1\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "VENV~1\lib\site-packages\modeltranslation\manager.py", line 405, … -
Django ready HTML website templates
I have Django installed along with Jinja2 and cookiecutters. I want to use some frontend templates for my website. Right now I am creating the styling by myself using Bootstrap CSS. I am aware of Bootstrap website templates but was wondering if there are any frontend templates ready for Django tags filters and so on. I have been looking at gitbub but haven't found any. The type of website I want is with login system etc. (Not a blog) -
How to best use your own Models in Django-CMS?
I'm pretty new to Django-CMS (v3.4.6) (and Django (v1.11), and Python (v2.7.x)) and I'm not even sure I'm asking the right question, so let me recap a bit: I have to build a site which will be mostly dependent on model instances, so I started creating my models and adding them to Django's admin page, so far so good. But then when I went and tried to use these models in my pages, I couldn't really find a simple way to do it. My first attempt was to simply use the Pages as my models and use plugins in placeholders, but then I realized that for each language translation I would have to put the contents again, even for plugins that don't need a translation. (For example, I have a few ManyToMany relations to pick elements of a list, and said elements can just return their properly-localized text, so it makes no sense to ask content editors to click the same items in a list once per language. Or is it monumentally wrong to have a text field for each language in a PluginModel?) I also tried gathering all the fields required for a page into a single model and … -
ImportError: No module named django even though Django is installed
When I write pip list, I can see django there. When I write import django in python shell, there is no error. But when I write python manage.py runserver it gives me the following error: Unhandled exception in thread started by <function wrapper at 0x105838b18> Traceback (most recent call last): File "/Users/manitgupta/virtualenvs/testify/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Users/manitgupta/virtualenvs/testify/lib/python2.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run autoreload.raise_last_exception() File "/Users/manitgupta/virtualenvs/testify/lib/python2.7/site-packages/django/utils/autoreload.py", line 250, in raise_last_exception six.reraise(*_exception) File "/Users/manitgupta/virtualenvs/testify/lib/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/Users/manitgupta/virtualenvs/testify/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/manitgupta/virtualenvs/testify/lib/python2.7/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/manitgupta/virtualenvs/testify/lib/python2.7/site-packages/django/apps/config.py", line 127, in create import_module(entry) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named django -
django added at end of app names automatically
I am learning Django but have encountered a problem while adding apps to Installed apps in settings.py I added 'polls' app INSTALLED_APPS = [ 'polls.apps.PollsConfig' 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', but an error has occurred which says ImportError: No module named 'polls.apps.PollsConfigdjango'; 'polls.apps' is not a package when I write only 'polls' instead of 'polls.apps.PollsConfig' the following error occurs `ImportError: No module named 'pollsdjango' the name of app I am trying to import is 'polls' -
Right align multiple texts within Bootsrap 4 breadcrumbs
I want to create a breadcrumb using Bootstrap 4.1 so that the site map path shows on the left, and register and login links on the right. The following is a schematic view of what I want to achieve: Home/Blog/post Register/Login By following this, I could use ml-auto to move the "Login" link to the right. If I use ml-auto on "Register", it shows up in the middle. My code: <nav aria-label="breadcrumb"> <ol class="breadcrumb"> <li class="breadcrumb-item"><a href="#">Home</a></li> <li class="breadcrumb-item"><a href="#">Blog</a></li> <li class="breadcrumb-item active">post</li> <li class="ml-auto">Register</li> <li class="ml-auto">Login</li> </ol> </nav> which gives me: Home/Blog/post Register Login -
Nginx + Gunicorn + Django 504 Error
I am running Nginx + Gunicorn + Django on Azure. Everything seems to run fine, all the views are rendered pretty quickly, but every 2-3 weeks I get a 504 Timeout error on all of my requests to ANY of views, and have to restart Gunicorn to fix it. There's a lot of advice on here about increasing the timeout on Nginx and Gunicorn but I don't see that as a solution because this is NOT a single long view. I noticed that the problem is sometimes correlated with network traffic in (looking at the Azure monitoring). For example, when I get a giant network in increase like 4 GB at once, I start getting the timeouts. I looked into my Nginx config file and noticed this: client_max_body_size 4G; So I changed it to this: client_max_body_size 30m; My app needs to handle uploads of documents and large images sometimes, so I figured 30 MB would be a decent limit. The problem hasn't reoccurred yet but I can't tell if I actually fixed the issue or not. Are there any other possibilities for why this problem would be occurring that I should look at? -
python sqlalchemy upsert ignore rows
I'm using the upsert option of Postgres in Django. from sqlalchemy.dialects.postgresql import insert insert_statement = insert(...) session.execute(insert_statement.on_conflict_do_update(...).values(rows)) The rows variable contains about 1000 entries, so if one of them causes any trouble, then an exception is thrown in nothing is inserted/updated. I've tried to run the statement in a loop for every single row in rows but that makes it extremely slow. Is there a possibility to ignore rows that cause an exception in the on_conflict_do_update method (or some other way) and still perform the action for all other rows? -
RelatedField Serializer Django Rest Framework
I have this tables store in a Postgres DB users | id | email | password | gender | | 01 | user1@email.com | pass1 | male | | 02 | user2@email.com | pass3 | female | | 03 | user3@email.com | pass2 | male | marks | id | school_mark | subject | user_id | status | | 01 | 9 | history | 01 | True | | 02 | 8 | english | 02 | True | | 03 | 7 | math | 01 | True | | 02 | 7 | english | 01 | False | | 03 | 6 | math | 03 | False | ... user_id is a foreign key that links the marks element to each user id (in both table) are primary keys my_app/models.py from django.db import models class User(models.Model): email = models.EmailField() password = models.CharField(max_length=100) gender = models.CharField(max_length=100) class Mark(models.Model): school_mark = models.IntegerField() subject = models.CharField(max_length=100) user_id = models.ForeignKey(User, on_delete=models.CASCADE) status = models.BooleanField(default=False) I want my final result to be like this /api/marks/male [ {"id" : 01, "marks": [ {"id": 01, "subject": "history", "school_mark": 9}, {"id": 03, "subject": "history", "school_mark": 7}]} {"id" : 03, "marks": []} ] First … -
django-allauth : remove the password field in signup form
I'm using django-allauth in my project, coupled with Django-sesame from login, which sends links by emails for users to login without password. However, django-sesame does not handle signups. I am trying to remove the password fields from the signup form, since passwords are not used for login. I only want users to have to input their email adresses. Here's what I've got: FORMS.PY class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = ('username', 'email',) MODELS.PY class CustomUser(AbstractUser): # Add additional fields here. For example, a global-friendly name field # name = models.CharField(blank=True, max_length=255) def __str__(self): return self.email This code works, but I've tried everything found on the internet and I've not been able to remove the passwords fields. For what it's worth, I would be okay with putting a dummy password for every user, and hide the field, since users must login through the token email auth. Thank you! -
Django-taggit TaggableManager() producing Admin error
I'm working through the book Django 2 By Example, in which I'm trying to build a blog application with tagging functionality. My code for including django-taggit (after installing version 0.22.2 with pip) is the following. Add the app to INSTALLED_APPS: INSTALLED_APPS = [ #... 'blog.apps.BlogConfig', 'taggit', ] Add TaggableManager provided by django-taggit to Post model. from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse from taggit.managers import TaggableManager # Create your models here. class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager, self).get_queryset().filter(status='published') class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField(default='') publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() # The default manager. published = PublishedManager() # Our custom manager. tags = TaggableManager() def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) class Meta: ordering = ('publish',) def __str__(self): return self.title When I add the line tags = TaggableManager() to the Post model, I get the following error when trying to add a new post or edit an existing post via the admin site: TypeError: render() got an unexpected keyword argument … -
DJANGO - simple-history - how to look up history table from base model using standard django ORM lookup
This is probably a simple answer but I cant find a solid "yes" or "no" on the subject. I am using Django simple-history and I am trying to filter the base model objects by information in the history table. Because simple-history generates the history table automatically, and I didn't create a history model for it per-se I dont know if the django ORM lookup syntax works here. My table relations look like this. Here's the model: class RepairForm(models.Model): user_id = models.ForeignKey(User, on_delete=models.DO_NOTHING,) return_number = models.CharField(max_length=200, unique=True) incident = models.CharField(max_length=100, blank=True) ... # Simple-history history = HistoricalRecords() And I am trying to filter RepairForm objects by their history. As an example; there is a field in only the history table called "history_change_reason." It's just a field for saving a string that (ideally) describes why the update happened. Referencing the table image I linked, I thought I could filter down RepairForm objects using the RepairFormHistory table by traversing the relationship they both had with the user table. Something like: RepairForm.objects.filter(user_id__repairformhistory_history_change_reason='Custom Repair form page') "repairformhistory" was my best guess as to what the history model (if there is one) is called. The error: Related Field got invalid lookup: repairformhistory_history_change_reason Am I way off … -
How to display data from mongodb to django admin panel in the from of table or dasboard?
I am currently working on Django and MongoDB. I would like to upload CSV file in MongoDB and I want to show that data in Django admin panel. What are the methods for doing this task also is it possible to make a dashboard on admin panel to represent that data? I am using, Django v2.0.7 MongoDB v4.0 Please help -
How to add chained dropdown in models.py in Django?
I am new in python and Django. I want to make a directory list website. Only admin can add, edit or delete content. I am creating the website with Django. I need to add chained dropdown to models.py. How can I do it? I am beginner, so please explain deeply if possiple :) I will do the same for front-end. For example: Study field: Engineering, Economics, Design Subject: If engineering is selected then -> Mechanical engineering, electric engineering and etc. -
How to ask for Google Calendar consent after someone schedules a lesson instead of when someone signs up
Context: I am building a Django project where users can sign in with google and python-social-auth is helping me do so. I am building a website where people can schedule events. So I thought of adding a new feature where when someone schedules an event with another person, it's going to schedule that event in both of the peoples' calendars if they are signed in with google. The actual problem: When someone signs up with google on my site, it asks them to pick an account and immediately asks for consent to their google calendar. I am worried that for a newcomer on my site this may scare them, so what I would like instead is if consent to their google calendar is only asked IF they schedule an event. Is there a way to do this? And as an extension to the question, should I ask for consent as soon as someone signs up or should I do it when they schedule an event. -
Auto add new model_field on request in Django || DRF
I have a simple REST-API project. Here is my models: class Human(Model): height = IntegerField() And I have a serializer for that: class HumanSerializer(ModelSerializer): id = IntegerField(read_only=True) height = IntegerField(required=True) Very clear and simple! But! What I want is to be able to add additional fields to my Human model, and automatically migrate those changes to the database, and add a new field to serializer that would be related to the new model field. For example, lets say that the client want to add a new field called "weight". So a developer won't do anything, because the backend will automatically receive that request, will automatically create a new field to Human model, automatically create a new field to serializer, and automatically create a migration.py file related to those changes. Is there a way to achieve that ? What is the best way to do that ? -
Replicate django admin for plain users
I would like to replicate django admin and its functionality for plain users(not staff memebers). So data models that I have would be shown in tables like in django admin, with filters and sortings per column. Even the look(templates) would be the same or similar. Also login and registration should be the same. How could I replicate that without doing it all from ground up, making views, templates etc? -
How to optimise function with function calls inside python
I have a function which loops and fetches data from another functions. I tested this api call from postman it returned data in 750ms but as this call is important call and it needs to be more optimised. I tried threading but I could not reduce time (maybe I was not implementing threads correctly). Please any type of solution is appreciated. My main function is :- class QuoteDetailsList(APIView): permission_class = default_permissions def get(self, request, format = None): try: try: source = LOCAL_DATA_SOURCE fiat = request.GET.get("fiat", False) if source not in ALLOWED_SOURCES: source = GLOBAL_DATA_SOURCE except Exception as e: log_exception(e) source = LOCAL_DATA_SOURCE fiat = False # MarketDataInterface().getAllQuotes(source, fiat) return Response(MarketDataInterface().getAllQuotes(source, fiat), status = status.HTTP_200_OK) return Response(data=dict(msg="KAR raha hun bhai")) except InvalidDataError as e: return Response({'error' : str(e)}, status.HTTP_400_BAD_REQUEST) except BaseCryptoException as e: return Response({'error' : str(e)}, status.HTTP_503_SERVICE_UNAVAILABLE) getAllQuotes() :- def getAllQuotes(self, source, isFiat = False): result = [] thr = [] if not isFiat: symbols = Symbol.objects.all() else: symbols = Symbol.objects.exclude(Q(baseCurrency__isCrypto=True) | Q(quoteCurrency__isCrypto=True)) for symbol in symbols: try: if not symbol.baseCurrency.isBaseCurrency: continue result.append(self.getQuote(symbol.symbolId, source, symbol)) except Exception as e: print("error",e) pass return result Ignore if conditions the next function running is getQuote getQuote :- def getQuote(self, symbolId, source, symbol = …