Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I display my static files in my html from django
I have created my static folder and uploaded images into my images folder. The local server runs alright but the image is not able to display when i call the path to it in http://127.0.0.1.8000/static/images/theimage.jpg -
SuspiciousFileOperation at /media/C:/fakepath/example.png when submit from angular
I'm building an Angular + Django project, where the user can upload a file to a model: Model: def upload_path(instance, filename): return '/'.join(['files', str(instance.titulo), filename]) class File(models.Model): titulo = models.CharField(max_length=154, null=False, blank=False) file = models.FileField(upload_to=upload_path, null=False) When I send a post request through Insomnia , everything is Ok, the file is saved in the media root(media), but when I send through Angular the path that it saves is similar to the title, and that errors occurs. Angular: <div class="row"> <label style="margin-left: 10px;">Anexos</label> <label id="label-input"> <input [(ngModel)]="ticket.file" type="file" single id="input-file"> </label> </div> Services: htttpHeaders = new HttpHeaders().set("Content-Type", "application/json").set('Authorization', this.token); public saveNewTicket(ticket): Observable<any> { return this.http.post(this.baseUrl + "ticket/", ticket, { headers: this.htttpHeaders }); } -
Django CMS: How to avoid SITE_ID to be set in settings?
We are using Django CMS for a while, and need to migrate our website to a multi-site implementation with Django Sites framework. We wanna use CurrentSiteMiddleware to detect which site is used (based on subdomain). In result we will have a request.site.id set by middleware that is based on the current user request to our website. I've tried to find the best way how to use Django CMS without forking it, and didn't find a good way how to do this. What do we actually need: each Page can be used on the current Site, or on few sites at the same time. To do so, Django documentation recommends to add M2M FK to the Site model from each Article object (in our case, it's the Page object). But the TreeNode has the FK to the Site model, that means that only one Page can be mapped to a single site. But we need to map one Page to one of few sites at the same time. we want to use Django Sites framework, because Django has it built-in and creators of Django use it on their projects (and it's for what is was designed - to map some object … -
Django creating a relation between 2 models manually seems impossible
I want to enable my users to add bookmarks for Posts and other elements to there account but sadly each time I check if there is already a Boomark present for a specific element I get back the following error: Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a GenericRelation. which again makes absolut zero sense to me as I manually set the relation exactly as desicbed here: https://docs.djangoproject.com/en/3.0/ref/contrib/contenttypes/#reverse-generic-relations I already ask this question several times at various forums and collegues but sadly nobody seems to understand the problem so far. I would really appreciate it if smb. has a good hint here as I got absolut stuck with this. Im on Django 3.0.4 and Python 3.8.2. models.py of App1 from App2 import UserBookmarks class Post(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Title", max_length=20) content = models.TextField(verbose_name="Post Content", max_length=2000) ... bookmarks = GenericRelation(UserBookmarks, related_query_name='post') models.py of App2 bookmarkable_models = models.Q(app_label='App', model='post') | models.Q(app_label='App', model='model-b') | models.Q(app_label='App', model='model-c') class UserBookmarks(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False) content_type = models.ForeignKey(ContentType, limit_choices_to=bookmarkable_models, on_delete=models.CASCADE, null=True, blank=False) object_id = … -
django framework mp3 audio file
i am making a website with a list of mp3 files and i want a detail view. the problem is django cannot find the mp3 file. it shows up in the source code and the audio bar shows up so i can play/pause adjust volume etc in download.html u see i use {{ object.file.url }} in a h1 tag, the url is right but django gives me a 404 error Gives a 404 error in the console. in html it also does not wrok because i use need a content object. i want the url to be http://example.com/download/(id) then the download.html shows and they can play the mp3 file or download it download.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Download</title> </head> <body> <audio controls> <source src="{{ object.file.url }}" type="audio/mpeg"> Your browser does not support audio </audio> <h1>{{ object.file.url }}</h1> </body> </html> views.py from django.shortcuts import render, get_object_or_404, reverse from .models import Song def index_view(request): queryset = Song.objects.all() context = { 'list': queryset } return render(request, 'index.html', context) def download_view(request, id): obj = get_object_or_404(Song, id=id) context = { 'object': obj, } return render(request, 'download.html', context) setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pages', ] MIDDLEWARE = [ … -
Django Rest API for models with "optional" Foreign Key
I have a model: models.py class Doctor(models.Model): doctor_name = models.CharField(max_length=264, unique=True) # on_delete argument needs to be researched more deeply. address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, blank=True) contact_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.") contact = models.CharField(validators=[contact_regex], max_length=15, null=True, blank=True) # validators should be a list qualifications = models.CharField(max_length=264, null=True, blank=True) license = models.CharField(max_length=264, null=True, blank=True) note = models.TextField(null=True, blank=True) def __str__(self): return self.doctor_name In this model "address" foreign-key field is optional. I want to create a rest API. But if I do not provide address fields, it gives the error. It works fine if I provide address fields. serializers.py class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__' class DoctorSerializer(serializers.ModelSerializer): address = AddressSerializer() class Meta: model = Doctor fields = ['doctor_name', 'contact', 'qualifications', 'license', 'note', 'address'] def create(self, validated_data): address_data = validated_data.pop('address') addr = Address.objects.create(**address_data) print(addr) doctor = Doctor.objects.create(**validated_data, address=addr) return doctor -
Using an annotation value in subsequent annotation throws FieldError
What I am trying to do: I have models Topic and Entry. Entry has a ForeignKey to topic. I need to list topics on condition that the user has entries in it (created in last 24 hours). I also need to annotate count, it needs to be the total number of entries created after the last entry written by the user. (To put it more thoroughly, you can think of an inbox where you have list of conversations with number of unread messages.) This's what I have come up with: relevant_topics = ( Entry.objects.filter(author=user, date_created__gte=time_threshold(hours=24)) .values_list("topic__pk", flat=True) .order_by() .distinct() ) qs = ( Topic.objects.filter(pk__in=relevant_topics).annotate( latest=Max("entries__date_created", filter=Q(entries__author=user)), count=Count("entries", filter=Q(date_created__gte=F("latest__date_created"))), ) ).values("title", "count") Which will throw: FieldError: Cannot resolve keyword 'date_created' into field. Join on 'latest' not permitted. I don't really know if Django itself doesn't support what I've written, or my solution is faulty. I thought adding count using .extra(), but I couldn't figure out how to use latest annotation there. I would really appreciate any query that produces the expected output. -
Django - email fields not listed after the call of .super().clean()
I'm new to Django and my apologies if this is to basic question (or mistake), but I'm having issues with email format validation when the email is typed like: test@com. I created the form.py and views.py below for test: form.py from django import forms from django.core import validators class userForm(forms.Form): fname = forms.CharField(label="First name") lname = forms.CharField(label="Last name") email = forms.EmailField(label="Email") vemail = forms.EmailField(label="Email validation") def clean(self): all_clean_data = super().clean() fname = all_clean_data['fname'].lower().capitalize() lname = all_clean_data['lname'].lower().capitalize() email = all_clean_data['email'].lower() vmail = all_clean_data['vemail'].lower() if email != vmail: raise forms.ValidationError("Email address doesn't match, please try again") views.py def users(request): form = forms.userForm() if request.method == 'POST': form = forms.userForm(request.POST) if form.is_valid(): print('Validation ok') return render(request,"test_app/users.html",{'formName':form}) Seems that everything is working fine ... but ... if in the form (webpage) I type an email address like: test@com and submit the form, 2 things happens: I do not get an alert like "Invalid email format" on the form (webpage) The email "key" on all_clean_data['email'] does not exists. If I type a valid email like: test@test.com, it works. If I type an invalid email address like: abcde, then I get an alert message. The issue is when I type things like: test@com ... then I … -
django website hangs in production apache+mod_wsgi+django
I'm deploying my first website with django. I've followed a lot of tutorials and documentations and now I'm stucked since I don't even know how to get information about the error. Please help me. SO: Centos7 python 3.7.6 apache 2.4.6 django 3.0.3 I developed the site with the development server and all works completely fine, no errors at all. This is my 'real project'. Installed httpd, and configured the firewall, allrighty the testing 123... page was shown. Then I followed the documentation about mod_wsgi to install it and deploy a 'hello world' web page as the docs sugested, everything worked all right. A blank page with 'Hello world' appeared. Then I prepared a 'new project' with django which worked fine with development server.(no surprise). Afterwards the 'new project' worked properly when using apache+mod_wsgi, I am able to access the admin site. Then I thought I would be able to deploy the website I developed before just edited the the same django.conf that I used with the 'new project' to pointing to the path of my 'real project'. But it didn't work. It just hangs till times out; it does nothing. I have no other website or similar so I didn't … -
No module named 'django' in standalone Django App
I have installed Django on Windows 10, Django Version 3, Python 3.8 from Conda, with env, on VS Code My Django works fine without any problem and my App and Project also works fine, but I decided to use Faker to generate some fake data in my DB, I have to mention that my Model works and connected successfully to my DB and migration process was successful without any problem. I write this Standalone app for Faker to run it whenever I need manually: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'first_project.settings') import django django.setup() # Implement Fake Population script here. import random from first_app.models import AccessRecord, Topic, Webpage from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Games'] def add_topic(): t = Topic.objects.get_or_create(top_name=random.choice(topics))[0] t.save() return t def populate(N=5): for entry in range (N): # Get the topic for the entry top = add_topic() # Create the fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() # Create the new webpage entry webpg = Webpage.objects.get_or_create(topic=top,url=fake_url, name=fake_name)[0] # Create a fake access record for that webpage acc_rec = AccessRecord.objects.get_or_create(name=webpg,date=fake_date)[0] if __name__ == "__main__": print('Population Script!') populate(20) print('Population Completed!') But whenever I run this code, I get … -
Send json data to frontend in Django Channels
I have the following consumer: client = Client('', '') trades = client.get_recent_trades(symbol='BNBBTC') class EchoConsumer(AsyncJsonWebsocketConsumer): async def connect(self): await self.accept() await self.send_json('test') def process_message(message): JSON1 = json.dumps(message) JSON2 = json.loads(JSON1) #define variables Rate = JSON2['p'] Quantity = JSON2['q'] Symbol = JSON2['s'] Order = JSON2['m'] print(Rate, Symbol) bm = BinanceSocketManager(client) bm.start_trade_socket('BNBBTC', process_message) bm.start() This consumer starts a websocket connection to a cryptocurrency exchange and retrieves some trades. With this code, i will see the trades appearing on my console, but i can't find a way to send them to my frontend. If i try await self.send_json('Test'), my frontend will receive the message, but i don't know how to send the trades that the websocket retrieves and prints to my console. I tried this: await self.send_json(Rate, Symbol) but that throws an await outside of async function error. Can someone help me fix this issue? Thanks in advance! -
Django: how to get Foreign key id?
I have 2 models as below class Product(models.Model): product_name = models.CharField(max_length=100) product_weight = models.CharField(max_length=30) class ProductImage(models.Model): product = ForeignKey(Product, on_delete=models.DO_NOTHING) How to extract product_id in ProductImage model? Thanks in advance. -
Auto save login user_id as a foreignkey using forrm.py in django
how to submit form which automatically take user_id of current active user as a Foreignkey with form.py file in django -
Django Template format date string
I have date fields in my content dictionary in ISO format ('Y-m-d') and want to display these fields using the "date" filter of Django Template but whenever I use the date filter the date is not displayed and without the date filter it is displayed. As per the documentation, the "date" filter requires datetime object for filtering. Is there any work around to apply the filter apart from changing the content before sending it to the template? -
name 'login' is not defined. python (django)
I have one problem, w want create user and after login. i create user but can't login. my error ---> name 'login' is not defined. from django.contrib.auth.views import login. I tried this too but it didn't work where do I have a problem and how can it be resolved? i couldn't find a way to solve the problem on Google. please help me, Thanks in advance. views.py from django.shortcuts import render from django.http import HttpResponse import datetime from django.contrib.auth import authenticate from home.forms import SignUp def regform(request): if request.method == 'POST': form = SignUp(request.POST) if form.is_valid(): form.save() email = form.cleaned_data.get('email') raw_password = form.cleaned_data.get('password1') user = authenticate(email=email, password=raw_password) login(request, user) return redirect('home') else: form = SignUp() return render(request, 'home/home.html', {'form': form}) models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import ugettext_lazy as _ from django import forms class UserManager(BaseUserManager): """Define a model manager for User model with no username field.""" use_in_migrations = True def _create_user(self, email, password, **extra_fields): """Create and save a User with the given email and password.""" if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): """Create and … -
Multiple db constraints in Django model not working
I'm having issues getting multiple constraints to work (in postgres, if it matters). Here is the Meta: class Meta: constraints = [ CheckConstraint( check=(Q(target_value__gt=0) & ~Q(target_metric=DEFAULT)) | (Q(enabled=False) | Q(status=IMPORTING) | Q(status=IMPORT_FAILURE)), name="positive_target_value", ) ] It would seem straightforward enough to me, but it ends up not working. Here is the generated SQL (pulled from the db itself): target_value > 0.0::double precision AND NOT target_metric::text = 'DEFAULT'::text OR enabled = false OR status = 20 OR status = 30 And here is proof that it should actually work (pulled from a django console, where the conditions are copied from the migration file): Folder.objects.filter(models.Q(models.Q(('target_value__gt', 0), models.Q(_negated=True, target_metric='DEFAULT')), ('enabled', False), ('status', 20), ('status', 30), _connector='OR')) web_1 | Out[5]: <QuerySet [<Folder: aDifferentFolder>]> Folder.objects.filter(models.Q(models.Q(('target_value__gt', 0), models.Q(_negated=True, target_metric='**SOMETHING DIFFERENT**')), ('enabled', False), ('status', 20), ('status', 30), _connector='OR')) web_1 | Out[7]: <QuerySet [< Folder: Folder aDifferentFolder >, < Folder: Folder thisFolderShouldNotHaveBeenCreted>]> Anybody has any suggestion? Btw, I also tried switching the first condition with the second one, effectively putting the AND at the bottom of the query, but it didn't seem to have any effect. Thanks a lot. -
Displaying email address during sign up process in django-allauth's verification_sent template
Using django 2.2.9, django-allauth 0.39.1, I am trying to optimize the sign-up procedure. In the sign-up form, the user is asked to enter the email address 1x and the password 2x. Although this is fine, some users still mistype their email address and therefore never receive the verification email. As a solution, I thought one could maybe customize the message in the verification_sent.html template. I created a new template, which is working fine. Now, I'd like to add to the text the email address the user entered in the previous step in the sign-up form. That way the user would be able to see the email address once again and repeat the sign-up process if they spot a typo. Does someone know if there is a way to do this? -
ModuleNotFoundError: No module named 'allauth' when trying to createsuperuser
So, im new to Django and for the sake of learning im trying to get a project up with allauth while extending AbstractBaseUser. The project starts, there is no problem there, the login screen from allauth displays my custom model (login with email). But when i try to create a superuser i get the following error. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\users\bramv\appdata\local\programs\python\python38\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\users\bramv\appdata\local\programs\python\python38\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\users\bramv\appdata\local\programs\python\python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\users\bramv\appdata\local\programs\python\python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\users\bramv\appdata\local\programs\python\python38\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\users\bramv\appdata\local\programs\python\python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'allauth' I did setup a virtualenv and installed django-allauth with pip and i followed the install instructions from the django-allauth docs. I fail to see where this error is comming from, any help would be greatly appreciated. -
How to fix Key Error when testing django create CBV?
I have been troubleshooting this problem for 3 days now. I think I'm missing something fundamental about testing Create Views or using client.post(). The test is failing because the date key is not present in the cleaned_data dictionary of the form, however, the code works correctly when executed from the browser. Can you please tell me why is the date key present in the cleaned_data dictionary when running in the browser but absent when executed by client.post() in the test? Below are snippets of relevant code. Models.py class Livestock(CommonInfo): """Model definition for Livestock. CommonInfo is an abstract model that contains created_by, modified_by, date_created, date_modified and comment fields""" product = models.ForeignKey( Product, on_delete=models.CASCADE, related_name='livestock') date = models.DateField( auto_now=False, auto_now_add=False) production = models.PositiveIntegerField( 'Livestock produced (Kg or litre or #)') number_of_animal = models.PositiveIntegerField( 'Number of Animals (Quantity)', blank=True, null=True) cost_of_production = models.PositiveIntegerField( 'Cost of Production (GYD)', blank=True, null=True) views.py class LivestockCreateView(LoginRequiredMixin, PermissionRequiredMixin, CreateView): model = Livestock form_class = LivestockForm success_url = reverse_lazy('real:livestock-list') template_name = "real/livestock/livestock_form.html" permission_required = ('real.add_livestock') def get_initial(self): initial = super(LivestockCreateView, self).get_initial() initial['date'] = timezone.now() return initial def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) Forms.py class LivestockForm(forms.ModelForm): """Form definition for Livestock.""" class Meta: """Meta definition for Livestockform.""" model = … -
Autofill foreignkey in Django Admin Inline
I have Employee shown inline with Company. Employee belongs to a Company and a company specific Department. I have to autofill the current company to the new Department form. # models.py class Company(models.Model): name = models.CharField(max_length=255) class Department(models.Model): name = models.CharField(max_length=255) company = models.ForeignKey("Company", on_delete=models.CASCADE) class Employee(models.Model): user = models.ForeignKey("User", on_delete=models.CASCADE) company = models.ForeignKey("Company", on_delete=models.CASCADE) department = models.ForeignKey("Department", on_delete=models.CASCADE) Edit Company Page New Department Popup -
Intergrating Django with React Frontend: Is a REST API Needed
so I am trying to connect my back-end Django to my front-end React. Now the front-end react is essentially completed and running on a node server to check it out. I want to integrate it into my Django to use as a back-end. My first thing i want to do is set up the login and register page. I have most of the django back-end done but now i need to get the information like the email and password from the React to Django. The HTML for EMail and Password <form action="/authentication/" method ="POST"> {% csrf_token %} Email : <input type="email" name="email"><br><br> Password : <input type="password" name="pass"><br><br> <input type="submit" value="Login"> <button type="button" onclick="location.href='{% url 'register' %}'">Register</button> </form> the react text field for just the email looks like this: <TextField variant="outlined" margin="normal" required fullWidth id="email" label="Email Address" type="email" name="email" autoComplete="email" autoFocus /> Django def user_login(request): return render(request, 'user_login.html') # page which user will login at def authentication(request): email = request.POST.get('email') passwrd = request.POST.get('pass') try: user = authen.sign_in_with_email_and_password(email, passwrd) except Exception as E: # Where login fails goes message = "Credentials Wrong" return render(request, 'user_login.html', {'message':message}) # sends message login failed My first question is do i need to create a separate … -
django jsignature not saving to database
i am trying to implement a jsignature plug in to my django appplication via django-jsignature3 , however it seems that i am unable to get it to save to my database. here is my code: models.py class JSignatureModel(JSignatureFieldsMixin): name = models.CharField(max_length=20) views.py def my_view(request): form = SignatureForm(request.POST or None) print('in view') if form.is_valid(): signature = form.cleaned_data.get('signature') print('form is valid') if signature: # as an image print('found sig') signature_picture = draw_signature(signature) # or as a file signature_file_path = draw_signature(signature, as_file=True) return render(request, 'cash/jsig.html', {'form': form }) jsig.html {% extends 'base.html' %} {% load static %} {%load crispy_forms_tags%} {% block content %} <body> {{ form.media }} <form action="." method="POST"> {% for field in form %} {{ field.label_tag }} {{ field }} <span style="color:red">{{ field.errors }}</span> {% endfor %} <input type="submit" value="Save"/> {% csrf_token %} </form> </body> {%endblock content%} url.py path('jsig/', views.my_view , name='jsig') forms.py (this is really iffy to me , i don't understand the documentation , there is no place that my model was called , hence i did this my self but it does not work) class SignatureForm(forms.Form): signature = JSignatureField() class Meta: model = JSignatureModel fields = ['name','signature'] exclude = [] here is my console [04/Apr/2020 01:14:43] "GET /jsig/ … -
Django Runtime Error while trying to run server
I am trying to run my Django server via 'python manage.py runserver' on a github repository i cloned and always get this runtime error message: class AbstractBaseUser(models.Model): RuntimeError: ____class____ not set defining 'AbstractBaseUser' as <'class 'django.contrib.auth.base_user.AbstractBaseUser'>. Was ____classcell____ propagated to type.____new____? Details of installed packages in my virtual environment are: Django 1.9 | django-crispy-forms 1.6.0 | django-markdown-deux 1.0.5 | django-pagedown 0.1.1 | markdown2 2.3.1 | olefile 0.46 | Pillow 7.1.1 | pip 19.2.3 | setuptools 41.2.0 | I am using python version 3.8.1 please does anyone have any suggestions on how to solve this error. Thank you. -
Can I remove the null=True parameter from a django ForeignKey?
I have two models, foo and bar. They already exists in my database with many instances each. Now, I realized that there is a relation that should be added. Therefor, I wish to add a ForeignKey betweenfoo and bar. class foo(): # lots of stuff bar = models.ForeignKey(bar, related_name='foo', null=True) I actually don't want the key to be nullable, but since they already exists, I need to add it because the existing rows need to be populated. Can I later remove the null=True parameter once all instances have the foreignKey field are populated? -
Setting value of certain attribute of a model related to User
I have a model related to User (relationship: OneToOne), in this model I have a field named email_confirmation. I can access to this field but I can't updated it. models.py class Profile(models.Model): profile_user = models.OneToOneField(User, ...) profile_email_confirmation = models.BooleanField(default=False) views.py def mail_confirmation(request, uidb64, token): uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) ... if user is not None and account_activation_token.check_token(user, token): user.profile.profile_email_confirmation = True user.save() #This isn't working and doesn't cause any error login(request, user) #This is working return redirect('/home') #This is working This function isn't causing any error so I don't know what is wrong I actually get redirect to /home (logged). I also can access to the field profile_email_confirmation When I check the model in the Admin page, the profile_email_confirmation field has not been altered.