Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I can't upload images from django admin to a directory that should simulate a static files live server?
When I upload an image from the admin panel I want this image to be uploaded in a specific directory in my Django project, still the directory is always empty. I changed my settings.py multiple times but I think the configurations of MEDIA_ROOT and MEDIA_URL are fine. static_cdn_test is the directory in my main Django project folder, it contains 3 directory: media, static, staticfiles. # relevant part of settings.py STATIC_URL = '/static/' LOCAL_STATIC_CDN_PATH = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn_test') STATIC_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles'), ] MEDIA_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'media') MEDIA_URL = '/media/' # my model class Article(models.Model): user = models.ForeignKey(User, default=1, null=True, on_delete=models.SET_NULL) image = models.FileField(upload_to='image/', blank=True, null=True) title = models.CharField(max_length=120) Inside static_cdn_test/media should appear a folder named image which should contains all the uploaded images but nothing happens. Any help is really appreciate, thanks all. -
Does the atomic decorator affect all the methods in the chain in Django?
I have the following models set up in Django: from django.db import models, transaction class X(models.Model): ... def do_something(self): ... self.save() class Y(models.Model): ... x = models.ForeignKey(X, on_delete=models.CASCADE) def do_something(self): ... self.save() def save(self, *args, **kwargs): super(Y, self).save(*args, **kwargs) self.x.do_something() class Z(models.Model): ... y = models.ForeignKey(Y, on_delete=models.CASCADE) @transaction.atomic def save(self, *args, **kwargs): super(Z, self).save(*args, **kwargs) self.y.do_something() Basically, whenever a Z object is saved, this triggers the do_something() method in the Y object, which then saves itself, and in doing so, triggers the do_something() method in the X object. I want the whole chaining to be atomic, so that if a Z object is saved, its corresponding Y and X objects must be saved as well. I have the decorator only in the save() method in the Z class. Is this the correct way to do this? Or, should the decorator be added to all the other methods in the chain? Does the decorator automatically affect all the methods in the chain or should it be explicitly added? Thanks for any help. -
How to get Foreign Key ID to show two models in DetailView?
I've created these two models: "Property" and "Bedroom". I've created a Class Based View, DetailView to show the details from Property, but now I need to show not only the property details but also the bedroom details. # models.py class Property(models.Model): property_reference = models.CharField(db_column='Property_Reference', max_length=10) # Field name made lowercase. address = models.CharField(db_column='Address', max_length=250, blank=True, null=True) # Field name made lowercase. post_code = models.CharField(db_column='Post_Code', max_length=15, blank=True, null=True) # Field name made lowercase. type = models.CharField(db_column='Type', max_length=25, blank=True, null=True, choices=HOUSE_TYPE_CHOICES) # Field name made lowercase. bedrooms = models.IntegerField(db_column='Bedrooms', blank=True, null=True) # Field name made lowercase. bathrooms = models.IntegerField(db_column='Bathrooms', blank=True, null=True) # Field name made lowercase. usual_cleaning_requirements = models.CharField(db_column='Usual_Cleaning_Requirements', max_length=250, blank=True, null=True) # Field name made lowercase. notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. feature_image = models.ImageField(null=True) class Meta: db_table = 'Property' def __str__(self): return self.property_reference def get_absolute_url(self): return reverse("properties:property_detail",kwargs={'pk':self.pk}) class Bedroom(models.Model): type = models.CharField(db_column='Type', choices=BEDROOM_TYPE_CHOICES, max_length=50) bed_dimensions = models.CharField(db_column='Bed_Dimension', choices=BED_DIMENSION_CHOICES, max_length=30) image = models.ImageField(null=True, blank=True) ensuite = models.BooleanField(default=False) notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase. property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE, related_name='bedroom') And I've created this view: class PropertyDetailView(DetailView): template_name = 'properties/property-detail.html' model = Property def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context['bedrooms'] = Bedroom.objects.get(property = … -
Django: How to Set Default Field Value By Model Method
I have a simple Model. I want to calculate a default value for one of its fields (let's call it score) based on the some of the fields of the same model: My ideal way to do it is as so: class ModelA(models.model): field_1 = models.IntegerField() field_1 = models.IntegerField() score = models.IntegerField(default=self.calculate_default()) def calculate_default(self): default = (self.field_1 + self.field_2) / 2 return default Problem: the calculate_default method does not have access to self. One solution I tried was overriding the save() method. The problem is that it prevents the user to further change the score field. Another method I searched was to override the inti of the class. But according to django it might have consequences if not implemented correctly. What is the cleanest way to achieve this? How can I set the default of a field to be calculated from other fields of the same model such that it could be later changed by the user? I have a hunch that classmethod is the way to go but I haven't been able to pull it off yet. -
Get and transfer data using an API
I have to develop an API to manage data between my Database in PostGreSQL and my website in Django. I'm actually looking for the best way to manage and transfer this data, what I actually found on different topics / sites is the Django Rest Framework to develop a Rest API in Django, here I would use a JavaScript framework for the front like React, Angular or VueJS (any tips about which one to choose ? ). I was wondering if there was other solutions that would be interesting ? I've been searching about FTP or things like this. Thanks, -
how to set a timezone.now on django
Hello i'm strugling trying to set a variable with a date.today. I don't want to set an auto_now i want to set a variable with the date of the access of the user. i'm not quite shure if i should create a Field with an function by default or just set a variable on views.py i've tried both and i'm getting lost models.py: task = models.CharField(max_length=150) topic = models.CharField(max_length=150) how = models.TextField(max_length=600) start = models.DateField(blank=False, auto_now_add=True) end = models.DateField(blank=False) updated_at = models.DateTimeField(auto_now=True) views.py: class DetailView(DetailView): template_name = 'details.html' model = To_do now = datetime.today def get_queryset(self): return To_do.objects.annotate( delta2=ExpressionWrapper(F('end') - F('now'), output_field=DurationField())) i want to get the today date to display a countdown (end - now) every time the user open the page -
Catch Django order_by exception
I want to let user get objects by sorting them via API: example.com/foo?sort_by=STR. I'm going to use STR in .order_by. I found it's difficult to catch FieldError if Django cannot sort by STR (if STR keyword doesn't exist in the field) because QuerySets are lazy. foo_set = Foo.objects.order_by('bar') # won't throw an exception return foo_set[: 10] # will throw FieldError I cannot check if STR field exists before because I want to let user sort in the reverse sequence (foo.order_by('-bar')). So I put foo_set[0] in try but it's horrible (exception if foo_set is empty, hardcoded getting the first element). What way to check would you use? -
Why I'm not able to open django app on heroku?
I'm trying to test out my app but uploading it to heroku but when I try to open it the following error appears I tried to heroku restart but nothing changes I have already pushed it and made it live, is just when I try to open it 2019-08-05T10:28:35.985995+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=gentle-badlands-35223.herokuapp.com request_id=1a6f1655-5d02-43c7-b629-c2b4897e76bf fwd="83.174.32.242" dyno= connect= service= status=503 bytes= protocol=https 2019-08-05T10:28:36.411718+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=gentle-badlands-35223.herokuapp.com request_id=d4d9f0e0-8495-43e2-929b-8664f88503e7 fwd="83.174.32.242" dyno= connect= service= status=503 bytes= protocol=https 2019-08-05T10:29:31.130647+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=gentle-badlands-35223.herokuapp.com request_id=2f3ab1c6-7b2f-47fd-827e-c4fc1725eda3 fwd="83.174.32.242" dyno= connect= service= status=503 bytes= protocol=https 2019-08-05T10:29:31.390998+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=gentle-badlands-35223.herokuapp.com request_id=088bbe15-3618-48d9-8c59-3a0d88d170f1 fwd="83.174.32.242" dyno= connect= service= status=503 bytes= protocol=https -
Import File in django
Here"s an Error I have and I can't solve: Cannot import name "File" from 'uploadapp.models' The picture below makes it better to understand. Thanks in advance for your help. enter link description here -
import xls file by django in problem in date field is not import in database
I was upload by admin django by select excel file that in available date but no fetch the date by excel file and not import date. -
How to manage the separate session for same browser Admin & Frontend in django
I'm looking for a way to separate the session handling for the admin part of a site and the frontend. A person should be able to log in to the admin (only if he has is_staff and/or is_superuser). He should have to be able to login with another username into frontend. So basically it's like two separate sessions for the admin and frontend. Login/Logout and Permission-check functionality is not a problem, different sessions is the problem. Any ideas? Thanks, -
when in try to access mysql view using django model it throws an error
I want to access the records in mysql view using django filter but it throws an error try: p = PartnerPayBillSummaryDetails.objects.all() print(p) except Exception as e: print(e) Error: OperationalError: (1054, "Unknown column '66_1_partner_pay_bill_ageing_dtl.id' in 'field list'") -
django.urls.exceptions.NoReverseMatch on deleteview
I am deleting a post using generic DeleteView. On clicking the link for delete it returns django.urls.exceptions.NoReverseMatch: Reverse for 'postdelete' with no arguments not found. 1 pattern(s) tried: ['posts/(?P[0-9]+)/delete/$'] I tried placing the before and after /delete/ #urls.py path('posts/<int:id>/delete/',blogpostDelete.as_view(),name='postdelete'), #DeleteView class blogpostDelete(DeleteView): success_url='/posts/' template_name="blog/delete.html" def get(self,request,id) : Blogpost = get_object_or_404(blogpost,id=id) return self.render_to_response({'id':id}) #link in template <a href={% url "postdelete" id=id %}>Delete</a> #delete.html {% block content %} <form action={% url "postdelete" %} method="post"> {% csrf_token %} <p>Are you sure you want to delete "{{ id }}"?</p> <input type="submit" value="Confirm"> </form> {% endblock %} -
How to trigger session deletion automatically after it expires?
I need to delete expired sessions from database. Similar Stack Overflow threads seem to suggest introducing a scheduled task (cron, Celery etc.) to run a check on expired sessions and delete them. However, I want to avoid introducing heavy stack for such simple task and am looking for a "native" way to delete a session from a database AS SOON AS it expires. So I have a pre_delete signal set on Session model that triggers the deletion if model's instance is expired. But there is one step remaining: I need Django to run delete on the instance as soon as it expires. Ideally, I would need a method like request.session.on_expiry(some_function_that_deletes_a_session_from_db). Is there a way to do this? -
how to add custom user field in User of admin page of django?
Will anybody help me? I have tried so much. I have read documentation but not understanding how to add custom user field in User of admin page? Whenever I makemigrations, it gives me following error. Different pages #admin.py from django.contrib.auth.admin import UserAdmin admin.site.register(UserProfile, UserAdmin) #models.py from django.contrib.auth.models import AbstractUser class UserProfile(AbstractUser): Id_card_number = models.CharField(max_length=15) #forms.py class UserRegisterForm(UserCreationForm): email = forms.EmailField(required=True)._unique = True Id_card_number = forms.CharField(max_length=15, required=True)._unique = True class Meta: model = UserProfile fields = ['username','email','password1','password2','Id_card_number'] Error whenever I use AUTH_USER_MODEL = 'users.UserProfile' in settings.py ERRORS: auth.User.groups: (fields.E304) Reverse accessor for 'User.groups' clashes with reverse accessor for 'UserProfile.groups'. HINT: Add or change a related_name argument to the definition for 'User.groups' or 'UserProfile.groups'. auth.User.user_permissions: (fields.E304) Reverse accessor for 'User.user_permissions' clashes with reverse accessor for 'UserProfile.user_permissions'. HINT: Add or change a related_name argument to the definition for 'User.user_permissions' or 'UserProfile.user_permissions'. users.UserProfile.groups: (fields.E304) Reverse accessor for 'UserProfile.groups' clashes with reverse accessor for 'User.groups'. HINT: Add or change a related_name argument to the definition for 'UserProfile.groups' or 'User.groups'. users.UserProfile.user_permissions: (fields.E304) Reverse accessor for 'UserProfile.user_permissions' clashes with reverse accessor for 'User.user_permissions'. HINT: Add or change a related_name argument to the definition for 'UserProfile.user_permissions' or 'User.user_permissions'. Error whenever I don't use AUTH_USER_MODEL = 'users.UserProfile' in settings.py … -
Is it safe to store OAuth credentials in request.session?
I need to store OAuth access token in between requests. I am currently doing something similar to this: def store_token(request): access_token = some_obtained_access token request.session['access_token'] = access token return HttpResponse('Token stored') Is it safe? If not, what other approach could I use to store the token in between requests? -
How to fix " 'user' is not a valid UUID."
I have created my own user model and there I have created a field named Unique_id and this is a uuid field and the primary_key=Trueand after creating a user I am getting this error ["'1' is not a valid UUID."] This is my custom user model class User(AbstractBaseUser): username = models.CharField(max_length=200, unique=True,) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) email = models.EmailField(unique=True) mobile_phone_number = models.CharField(max_length=20, unique=True) profile_photo = models.ImageField(default='media/default.png', upload_to = user_directory_path) unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key = True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) moderator = models.BooleanField(default=False) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['firstname','lastname','email','mobile_phone_number'] objects = UserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.staff @property def is_active(self): return self.active @property def is_admin(self): return self.admin @property def is_moderator(self): return self.moderator After creating a user I am getting this error. Exception Type: ValidationError Exception Value: ["'1' is not a valid UUID."] -
Apache + Django can not read css (403 error)
I want to publish a web app with Django + Apache + mod_wsgi. The app has been published but can not read static files. The version used is as follows. Windows10 Python==3.7.1 Django==2.2.3 Apache==2.4 We have confirmed that it works with Django's development server. I collected the files in one place using collectstatic. [httpd.conf] Alias /static/ C:/users/10001205180/Programs/katakan/deploy/ <Directory "C:/users/10001205180/Programs/katakan/deploy"> Require all granted </Directory> WSGIPythonPath C:/users/10001205180/programs/katakan SetHandler wsgi-script WSGIPythonPath C:/users/10001205180/Programs/katakan/myvenv/Lib/site-packages WSGIScriptAlias / C:/users/10001205180/programs/katakan/mysite/wsgi.py <Directory "C:/users/10001205180/programs/katakan"> <Files wsgi.py> Require all granted </Files> </Directory> [error.log] (Apache) [Mon Aug 05 18:31:05.015949 2019] [wsgi:error] [pid 3396:tid 1184] [client 10.5.150.3:58977] Options ExecCGI is off in this directory: C:/Users/10001205180/Programs/katakan/deploy/mainteboard/css/base.css, referer: http://10.5.150.3:8000/mainteboard/ [Mon Aug 05 18:31:05.028951 2019] [wsgi:error] [pid 3396:tid 1180] [client 10.5.150.3:58991] Options ExecCGI is off in this directory: C:/Users/10001205180/Programs/katakan/deploy/mainteboard/css/calendar.css, referer: http://10.5.150.3:8000/mainteboard/ [Mon Aug 05 18:31:05.028951 2019] [wsgi:error] [pid 3396:tid 1176] [client 10.5.150.3:58993] Options ExecCGI is off in this directory: C:/Users/10001205180/Programs/katakan/deploy/bootstrap_datepicker_plus/css/datepicker-widget.css, referer: http://10.5.150.3:8000/mainteboard/ [Mon Aug 05 18:31:05.038948 2019] [wsgi:error] [pid 3396:tid 1172] [client 10.5.150.3:58994] Options ExecCGI is off in this directory: C:/Users/10001205180/Programs/katakan/deploy/bootstrap_datepicker_plus/js/datepicker-widget.js, referer: http://10.5.150.3:8000/mainteboard/ [wsgi.py] import os from django.core.wsgi import get_wsgi_application import sys sys.path.append(os.path.dirname(os.path.abspath(__file__))) sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..' ) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() When opened in a browser, a 403 error occurs. I thought that there was … -
i want know how applicat css in my login.html
hello my friend i install bootstrap in my poject adn he works fine just i want to know how i can apllicate this bootstrap style with css and adapt it to my login.html thank you {% extends 'base.html' %} {% block content %} <div class="container"> <div class ="row text-center"> <div class="col-md-6 offset-md3"> <form action="" method="Post"> {% csrf_token %} <div class="form-group"> <label for="username">Nom d'Utilisateur</label> <input type="text" class="form-control" name="username" placeholder="Tapez le Nom d'Utilisateur"> </div> <div class="form-group"> <label for="password">Mot de Passe</label> <input type="password" class="form-control" name="password" placeholder="Mot de Passe"> </div> <button type="submit" class="btn btn-primary">Entrer</button> </form> </div> </div> </div> {% endblock %} -
Testing views with 'logged in user' without accessing database
I have written som arbitrary code to test a view-class with and without a logged in user. However, while doing that I have to create a user, which accessed the database. To follow good practice for TDD unittests I would try to avoid accessing the database, but I don't know how I've briefly tried to patch different modules, but I haven't figured out exactly how or what to patch This is the solution I'm using today: @pytest.mark.django_db class TestTreaterProfile: """ get with anonymous get with logged-in user """ [...] def test_get_with_logged_in_user(self): status_code = [200] view_class = ClientProfile client = Client() user = User.objects.create_user("user", "my@email.com", "password") client.force_login(user) # create request and retrieve response request = RequestFactory().get("/") request.user = user response = view_class.as_view()(request, *[], **{}) assert response.status_code in status_code, "Should have status_code 200 - OK" The code works, I would just like to modify it so that it don't have to access the database. Thanks in advance for your help! -
enabled download button if file is available with JavaScript
I'm trying to implement some logic for my UI. First the download button is in disabled state after an image uploaded. Once the Image is processed and it will generate an text file in a particular directory which will updated in database. Once the converted file available the download button automatically need to be enabled. The refresh should need to be done only for the button not the whole page. I have already tried setTimeout but the issue is entire page getting refreshed. Thanks in advance. My project is under development with Django framework. -
Is it possible to access Django application running on my local host to be accessible by another computer on other networks?
I am developing a web application on my local computer in Django. Now I want my webapp to be accessible to other computers on other networks. -
Django: dropdown selecting a model in a generic view
I have a generic Django generic DetailView and I'd like to be able to render a dropdown via a django.form. The options are a list of objects that belong to the user. I can do this for ALL objects with something like Model.objects.all() in the form, but how can I filter out the options that belong to the user without being able to access the request.user from the form? I've seen an example where the queryset can be injected into the form: form = MyForm() form['field'].queryset = Model.objects.filter(user=user) But there is no place to really do this in a django generic view (is there?) -
How to complete user (set password) registration with email in django-allauth?
I would like to register the user with some basic info (Name, Company...) and email. After the user submits the form i would like to send an email with a link that takes the user to a page to set his password. I have tried with a solution from this question: Django AllAuth - How to manually send a reset-password email?. The email was send and the link inside the email is working, but i get an AssertionError on my site. The error is in /allauth/account/utils.py inside the setup_user_email(request, user, addresses) function. The line: assert not EmailAddress.objects.filter(user=user).exists() What am i doing wrong here? My models.py: from django.contrib.auth.models import AbstractUser from django.db import models from allauth.account.views import PasswordResetView from django.conf import settings from django.dispatch import receiver from django.http import HttpRequest from django.middleware.csrf import get_token class Kompanija(models.Model): naziv = models.CharField(max_length=50) adresa = models.CharField(max_length=50, blank=True) def __str__(self): return self.naziv class Meta: verbose_name = "Kompanija" verbose_name_plural = "Kompanije" class CustomUser(AbstractUser): ime = models.CharField(max_length=30, default='') prezime = models.CharField(max_length=30, default='') kompanija = models.ForeignKey(Kompanija, on_delete=models.CASCADE, null=True, blank=True) is_premium = models.BooleanField('premium status', default=False) def __str__(self): return self.ime + " " + self.prezime @receiver(models.signals.post_save, sender=settings.AUTH_USER_MODEL) def send_reset_password_email(sender, instance, created, **kwargs): if created: request = HttpRequest() request.method = 'POST' if … -
NoReverseMatch at /^users/login/ (Reverse for 'index' not found. 'index' is not a valid view function or pattern name.)
I set up a user registtation and authorization system to allow people to register an account and log in and out. the first error is about TypeError: login() got an unexpected keyword argument 'template_name', I fixed it ,but the second problem arises.like this: NoReverseMatch at /^users/login/ Reverse for 'index' not found. 'index' is not a valid view function or pattern name. Request Method: GET Request URL: http://localhost:8000/%5Eusers/login/ Django Version: 2.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'index' not found. 'index' is not a valid view function or pattern name. Exception Location: D:\learning-note\ll_env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 668 Python Executable: D:\learning-note\ll_env\Scripts\python.exe Python Version: 3.7.3 Python Path: ['D:\\learning-note', Error during template rendering In template D:\learning-note\learning_logs\templates\learning_logs\base.html, error at line 2 Reverse for 'index' not found. 'index' is not a valid view function or pattern name. 1 <p> 2 <a href="{% url 'learning_logs:index' %}">Learning Log</a> - 3 <a href="{% url 'learning_logs:topics' %}">Topics</a> - 4 {% if user.is_authenticated %} 5 Hello, {{ user.username }}. 6 {% else %} 7 <a href="{% url 'users:login' %}">log in</a> 8 {% endif %} 9 </p> 10 11 12 learning_log/urls.py from django.contrib import admin from django.urls import path, include urlpatterns =[ path('admin/',admin.site.urls), path(r'^users/', include('users.urls', namespace='users')), path('', include('learning_logs.urls',namespace = 'learning_logs')), ] …