Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django:TypeError : int() argument must be a string, a bytes-like object or a number, not 'NoneType' while getting value from the user
I'm working on a Django project where I upload a .csv extension file and i give a integer value in the dashboard while uploading the file, the value that I upload must be given to the variable sf that is in the Index request field, and this error popped up File "E:\Django_proj\mysite\visual\views.py", line 29, in index sf = int(request.GET.get('text1')) TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType' [06/Apr/2021 23:15:46] "POST /visual/index/ HTTP/1.1" 500 67471 views.py file contains: def index(request): if request.method =="POST" and request.FILES.get('file', False): file = request.FILES["file"] csv = pd.read_csv(file, error_bad_lines=False) sf = int(request.GET.get('text1')) #The error field samplingFrequency = sf; samplingInterval = 1 / samplingFrequency; time = csv['time'] amplitude = csv['amplitude'] fourierTransform = np.fft.fft(amplitude)/len(amplitude) # Normalize amplitude fourierTransform = fourierTransform[range(int(len(amplitude)/2))] # Exclude sampling frequency tpCount = len(amplitude) values = np.arange(int(tpCount/2)) timePeriod = tpCount/samplingFrequency frequencies = values/timePeriod plt.title('Fourier transform depicting the frequency components') plt.plot(frequencies, abs(fourierTransform)) plt.xlabel('Frequency') plt.ylabel('Amplitude') plt.show() fig = plt.fft() buf = io.BytesIO() fig.savefig(buf, format = 'png') buf.seek(0) string = base64.b64encode(buf.read()) uri = urllib.parse.quote(string) return render (request, 'visual/index.html', {"something": True, "frequency": frequencies, "amplitude" : amplitude }, {'data':uri}) else: return render (request,'visual/index.html') uploading a file in views.py def upload(request): if request.method == 'POST': … -
How do I make apriori algorithm with book recommendations?
For example in booking shop website I want to implement Apriori algorithm. it should be in python programming language. -
Django - Success Message Mixin Does not work on Login
I'm trying to display a success message on login using the SuccessMessageMixin but the message is not displayed. Is there any reason why this would happen? settings.py LOGIN_REDIRECT_URL = 'home' LOGIN_URL = 'login' LOGOUT_REDIRECT_URL = 'home' LOGOUT_URL = 'logout' urls.py from .views import HomeView, LoginFormView urlpatterns = [ path('admin/', admin.site.urls), path('home/', HomeView.as_view(), name = 'home'), path('login/', LoginFormView.as_view(), name = 'login'), ] views.py class HomeView(FormView): template_name = 'home.html' class LoginFormView(auth_views.LoginView, SuccessMessageMixin): template_name = 'login.html' success_url = 'home/' success_message = "You were successfully logged in." login.html <h4>Login to your Account:</h4> <div> <form action "" method = "POST"> {% csrf_token %} {{form}} <button type = "submit">Login</button> </form> </div> home.html {% if messages %} {% for message in messages %} {{ message }} {% endfor %} {% endif %} -
Can't filter objects by BooleanField in Django
I'm building a reminder and trying to filter Task objects by a BooleanField called 'status'. as you can see, I have assigned Task.objects.filter(status=False) to undone_tasks, but when I run it, I get this error: ProgrammingError at /showing-all-tasks/ argument of NOT must be type boolean, not type character varying LINE 1: ..."status", "task"."reminder" FROM "task" WHERE NOT "task"."st... This is the query running in postgres: SELECT "task"."id", "task"."user_id", "task"."title", "task"."slug", "task"."description", "task"."deadline_date", "task"."date_edited", "task"."status", " task"."reminder" FROM "task" WHERE NOT "task"."status" ORDER BY "task"."deadline_date" DESC when I change "task"."status" to "task"."status" = 'true' in pgAdmin, everything works fine! but im cofused! First of all: why do I get this error? secondly: if status is a BooleanField, why when I compare it a string('true') I don't receive any errors? thanks for the help! views.py class TaskListView(ListView): model = Task template_name = 'mysite/show_tasks.html' def get_context_data(self, **kwargs): context = super(TaskListView, self).get_context_data() undone_tasks = Task.objects.filter(status=False) return context models.py class Task(models.Model): # some other fields... status = models.BooleanField(verbose_name='Task Status', default=False) class ReminderNotification(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='user', related_name='owner_notifications') message = models.TextField(max_length=200, default="", blank=True, null=True, verbose_name='message') task = models.ForeignKey(Task, on_delete=models.CASCADE, verbose_name='task', related_name='task_reminder_notifications') -
Django 3 image and file upload not saving through form
i am trying to learn django and and when i try to save image and file using form it is not saving there is no error i do'nt know what i am doing wrong added this in settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' my view.py class home(View): def get(self, request): form = ResumeForm() return render(request, 'resume/home.html', { 'form':form}) def post(self, request): form = ResumeForm(request.POST, request.FILES) if form.is_valid(): form.save() return render(request, 'resume/home.html', {'form':form}) and my urls.py from django.contrib import admin from django.urls import path from resume import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.home.as_view(), name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Please can anyone help me -
Placeholder and view only values in Django model form
this has been asked a few times, but the answers don't seem to work on my code (all looks correct). How do I create 'placeholder' and 'view only' values (JS is inputting longitude and latitude values in my code). Thinking this is something to do with my 'fields' and 'labels' at the bottom. Placeholder value in the name field doesn't show (but form works fine). thanks! class SafezoneForm(forms.ModelForm): class Meta: model = Safezone name = forms.CharField(widget=forms.TextInput (attrs={'id':'name', 'class':'form-control', 'placeholder':'Whynoplaceholdershows'})) useremail = forms.CharField(widget=forms.EmailInput(attrs={ 'id': 'useremail'})) latitudecentre = forms.FloatField(widget=forms.TextInput (attrs={'id': 'latcentre1'})) longitudecentre = forms.FloatField( widget=forms.TextInput (attrs={'id': 'longcentre1'})) fields = ['useremail', 'name', 'longitudecentre', 'latitudecentre'] labels = { "name": "Name of safezone", "useremail": "Alert Email", "latitudecentre": "Latitude", "longitudecentre": "Longitude", } -
Localhost returning site can't be reached in Vagrant
I'm using vagrant with django and my Vagrantfile.template has port forwarding as follows: config.vm.network "forwarded_port", guest: 80, host: 8080 However, when I use pm runserver, the localhost:8080 says the site cannot be reached. I also tried using postman to test one of the DRF endpoints and I get the following error Error: connect ECONNREFUSED 127.0.0.1:8080 Would anyone know how to fix this? -
Django inspectdb adding new data to already implemented database
I need to add more data to an existing postgres database integrated in django from R and then run the inspectdb command in python. However, when trying inspecdtb, this gives me the error: ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the NAME value. 1 Is it possible to run the inspectdb if I just an add an table to an existing Django database? Or would I need to create a new database which I upload the new data to. Database config in settings.py: POSTGRES_DB = os.environ.get('POSTGRES_DB', default = "") DATABASES = { "default": { ..... "NAME": POSTGRES_DB ..... } -
Django - query dataset to find latest day and use as filter in one query
I have an app currently which contains a scraper that runs every 2 days. When the app launches I populate a table with just the most recently scraped data (based on the scraped_date). Currently I am doing this in 2 queries, one to find the latest date and the second to query for the objects, but I am wondering if there is a way to make it more efficient as it currently takes a couple of seconds to run which slows down the webpage load time. Query 1: last_day = getattr(Posts.objects.latest('scrape_date'),'scrape_date') Query 2: data = Posts.objects.values('col1','col2','col3','scrape_date').filter(scrape_date__gte = last_day) Thanks! -
Having Database design issues/Logic issues?
I am tasked with a new issue, and am having some logic/database design issues with the implementation, and actually figuring out if it's really possible without extremely complex work that's above my knowledge. (Im a Jr dev.). The general idea is that a Business has it's own Package table as follows, and a SalesReport gives the user the ability to select a package. I'll shorten some tables up for better readability. class Package(models.Model): business = models.ForeignKey(Business, null=True, blank=True)) name = models.CharField(max_length=256, null=True, blank=True) price = models.DecimalField(max_digits=8, decimal_places=2, null=True, blank=True) class SalesReport(models.Model): user = models.ForeignKey(Account, null=True, blank=True) package = models.ForeignKey(Package, null=True, blank=True) Only business owners have the ability to create these Packages. But when an employee is adding a SalesReport instance these Packages are shown in a dropdown, and the price field is pre-populated with the price field associated to the Package instance selected. Thats simple enough, yet the main task is to allow each employee to change the price field amount if they choose to, without modifying the Package instance itself the business owner originally created. So basically, if EmployeeA adds PackageA with a default price of $200 to their personal sales form, yet changes that $200 to $300, and … -
How to send mail when the date/time reached?
I have a django website which is integrated to sqlite database. It has a database table field with date/time stamp and email field. How to trigger a mail to user in email field with when the date/time field is equal to the current date/time. -
Django : format de date non valide avec Pandas - \xa0
Bonjour, J'aimerais créer des objets à partir d'un fichier CSV grâce à Django et Pandas. Tout se passe très bien pour les FloatField et les CharField mais lorsque je veux ajouter les DateField, Django rend cette erreur : ['Le format de date de la valeur «\xa02015/08/03\xa0» n’est pas valide. Le format correct est AAAA-MM-JJ.'] Pourtant le fichier CSV propose ce type de données pour les colonnes concernées : '2015/08/03'. Il n'y a pas d'espace dans les données comme semble le suggérer Django... voici ce que j'ai essayé dans views : class HomeView(LoginRequiredMixin, View): def get(self, request,*args, **kwargs): user = User.objects.get(id=request.user.id) Dossier.objects.filter(user=user).delete() csv_file = user.profile.user_data df = pd.read_csv(csv_file, encoding = "UTF-8", delimiter=';', decimal=',') df = df.round(2) row_iter = df.iterrows() objs = [ Dossier( user = user, numero_op = row['N° Dossier'], porteur = row['Bénéficiaire'], libélé = row['Libellé du dossier'], descriptif = row["Résumé de l'opération"], AAP = row["Référence de l'appel à projet"], date_dépôt = row["Date Dépôt"], date_réception = row["Accusé de réception"], montant_CT = row['Coût total en cours'], ) for index, row in row_iter ] Dossier.objects.bulk_create(objs) Si je change mon Model en CharField, je n'ai plus d'erreur. J'ai essayé d'utiliser la fonction str.strip(): df["Date Dépôt"]=df["Date Dépôt"].str.strip() Mais sans succès. Est-ce que quelqu'un pourrait m'apporter … -
How to have different settings.py locally and in production
I want to have different settings.py for when I run my project locally and in production, because I have a setting in settings.py that forces my project to use https, but django runserver.py can only use http, not https, so I am unable to run my project locally now. Also, I want to have debug=True on my computer, and debug=False in production. So how can I have a different settings.py for my computer and for production? -
Is it practical to learn Django and python for web development based on the job market?
My goal here is to stick to a language so that I can master it. One the one hand I know a little python and will explore ml, ai and ds but I might not make it a career. On the other hand the job market for Javascript is superior especially for web dev, mastering js would yield significant monetary benefits if go into web development. So is learning python for web dev not as bad or is javascipt and its frameworks a must for web dev. I know people advice to learn as much as possible and I will, but mastering any language or framework is a matter of months maybe an year. So I'd like to be certain of what to learn and practice with regular consistency. -
Django: using Images in Hyperlinks
im pretty new to Django (as in no Knowledge so far) and a project requires me to include a Image inside of a hyperlink. just including the inside of the hyperlinks created the error message 'blocktrans' doesn't allow other block tags (seen "static 'pretix_app/Instagram.png'") inside it my code so far is li ><img src="{% static 'pretix_app/YouTube.png' %}" alt="Youtube_icon" style="alignment: left;vertical-align:middle; width: 20px; padding-right: 5px" > {% with 'target="blank" href="https://www.youtube.com"'|safe as a_attr %} {% blocktrans trimmed %} <a {{ a_attr }}> Social Media-target {% endblocktrans %} {% endwith %}</li> This produces a working hyperlink, but does not include the image (which is required as a social media hyperlink) The "safe as attr"-method was copied from a working template included in the source code. Does anybody know if it is possible to include Images in Hyperlinks, and if yes, how? Thanks in advance for any help -
Direct Inline Foreign Key addition in Django Admin
I am editing the admin panel. I have my Story model and its rich content, whose model is StoryContent (I'm using Summernote). The problem is that when I try to add a Story instance, shows a select and it opens a new tab to add StoryContent. I would like the content of this tab to be displayed directly in the Story edit. My Models.py class StoryContent(models.Model): language = models.CharField(choices=LANGUAGES.choices, max_length=2) title = models.CharField(max_length=100, blank=True, default='') body = models.TextField() class Story(models.Model): ''' Multi language contents ''' content_es = models.ForeignKey( StoryContent, on_delete=models.CASCADE, related_name='article_es', ) content_en = models.ForeignKey( StoryContent, on_delete=models.CASCADE, related_name='article_en', null=True, blank=True ) content_pt = models.ForeignKey( StoryContent, on_delete=models.CASCADE, related_name='article_pt', null=True, blank=True ) Also this is my admin.py @admin.register(Story) class StoryAdmin(admin.ModelAdmin): ... fieldsets = ( ... ('Content', { 'fields': ('content_es', 'content_en', 'content_pt') }), ) The content selection is typical when adding a Foreign Key. This is an example image. What I want is that instead of showing a '+' with a selection, let me add directly the fields for each of the defined attributes. Can anyone help me? Ps. Sorry for my bad english! I'm doing my best. Feel free to edit my question. -
How to merge three models together, and use .all(), which gets all posts from those three models in django?
So, i have three models. Those three models are used for posts. when people click create posts, those models are triggered. Now i want to get the user's posts for all of those models. But i don't know how to do that all in one. i could do : current_user = request.user d = current_user.onemodel_set.all() # the onemodel is an example model d = current_user.twomodel_set.all() # the twomodel is an example model d = current_user.threemodel_set.all() # the threemodel is an example model but, i want to do this. d = current_user.allpostmodel_set.all() and the above should get the user's posts from all of those models, all grouped together. So could someone please help me with this? my three models class AskSection(models.Model): title = models.CharField(max_length=100) description = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) is_pin = models.BooleanField() likes = models.ManyToManyField(User, related_name='likes', blank=True) is_marked = models.BooleanField(default=False) date_posted = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_posted'] verbose_name_plural = "Ask Section" def __str__(self): return str(self.title) class TutorialsSection(models.Model): title = models.CharField(max_length=100) description = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name="likes_T", blank=True) date_posted = models.DateTimeField(default=timezone.now) class Meta: ordering = ['-date_posted'] verbose_name_plural = "Tutorials Section" def __str__(self): return str(self.title) class AnnouncementsSection(models.Model): title = models.CharField(max_length=100) description = models.TextField() user = … -
How to fetch all data from order table, but some data from order item table in django
I have two table Order and Order Items, and one order have many order items with multiple status like 'New', 'Cancelled', 'Delivered'. So when I fetch all orders which contains order items that only have status='New', then it returns all the order items that have status other than 'New' like 'Cancelled', 'Delivered'. So basically, it returns all the order items with particular order-id, it does not return partial order items against that order-id. Here is my code: order = Order.objects.distinct().filter(orderitem__status=request.data['status']) serializer = ListOrderSerializer(order, many=True) return Response(serializer.data) -
Properly setting custom Login Redirects in Django
I have a custom user model (subclassing AbstractUser): from django.db import models from django.contrib.auth.models import AbstractUser from django.utils.translation import ugettext_lazy as _ from .managers import UserManager class User(AbstractUser): username = None phone = models.CharField(max_length=16) email = models.EmailField(_('email address'), unique=True) is_director = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] And a custom view to handle the sign up form: class SignUpView(CreateView): template_name = 'form.html' form_class = UserRegisterForm form_title = "Family Registration Form" form_description = "For our younger participants, their parent or guardian should fill out this form." def get_success_url(self): return reverse_lazy('Participants:portal', kwargs={'slug': 'scst'}) Mapped by the following url: path('signup/', views.SignUpView.as_view(), name="signup"), The form loads and successfully creates a user. However, I can't figure out how to redirect properly. Specifically, I am looking for this: http://localhost:8000/scst/portal/ and am getting: http://localhost:8000/accounts/login/?next=/scst/portal/ I don't understand how to get rid of the /accounts/login/?next= portion. I have searched through CreateView's various Classes and Mixins. I have tried overriding the get_redirect_url and I have tried setting the pattern in the settings.py file. There is no "next" value in either the HTML's form or submit elements. I'm at a loss of what to change to fix this. -
'auto-create primary key used when not defining a primary key type' warning in Django
Hi I just updated my python from 3.9.1 to 3.9.4 (in an attempt to solve another bug that's already solved). When I tried to run the server. The console gave me a warning of this: . May I please know how do I fix this. I read the documentation about this but I dont understand how this part this page relates to this. Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): text = models.CharField(max_length = 200) date_added = models.DateTimeField(auto_now_add = True) image = models.ImageField(upload_to = 'backgroud_images', null = True, blank = True) owner = models.ForeignKey(User,on_delete = models.CASCADE) def __str__(self): return self.text class Entry(models.Model): topic = models.ForeignKey(Topic,on_delete = models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add = True) class Meta: verbose_name_plural = "Entries" def __str__(self): return self.text[:50] -
login form is not working. I am not able to login as a customer
The login form is not working. My signup form is working but LoginForm isn't. Whenever I login to the customer that error message is showing which is defined in an error_msg for debugging. forms.py class LoginForm(ModelForm): class Meta: model = Customer fields = ('email','password') widgets = { 'email': forms.EmailInput(attrs={'class': 'form-control form-control-sm'}), 'password': forms.PasswordInput(attrs={'class': 'form-control form-control-sm'}) } views.py def login(request): form = LoginForm error_msg = '' if request.method == 'POST': email = request.POST.get('email') password = request.POST.get('password') user = authenticate(request, email = email, password = password) if user is not None: login(request, user) return redirect('services') else: error_msg = "Email or Password Wrong!!" return render(request, 'core/login.html', {'form': form, 'error_msg': error_msg}) Login.html <form action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <!-- Button --> <div class="form-group text-center mt-3"> <button type="submit" class="btn btn-info btn-sm"> Login </button> </div> </form> can someone help me? Thanks -
Django + Angular: where to find an up to date application seed?
I'm looking into building a new Django (backend) and angular (frontend) application but struggle to find a seed that is up to date with the latest Django (as of today version 3.2). I have found several seeds but they seem very old e.g. 1.1.6 or so. Can anyone recommend a good up to date starting point? -
Gunicorn "module main not found" with Django in Google Cloud Shell
I'm working with Google Cloud for the first time, and after a very long day I'm turning to SO. I'm trying to follow this tutorial, but it keeps failing. I've succesfully completed every step, but when I try step 2.3; Run the Gunicorn HTTP server: ~/.local/bin/gunicorn -b :8080 main:app I get the following error: File "/home/jasper_wijnhoven/.local/lib/python3.7/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/jasper_wijnhoven/.local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/home/jasper_wijnhoven/.local/lib/python3.7/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/home/jasper_wijnhoven/.local/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/jasper_wijnhoven/.local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/home/jasper_wijnhoven/.local/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/home/jasper_wijnhoven/.local/lib/python3.7/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/usr/lib/python3.7/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 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'main' I changed nothing from the tutorial. My manage.py file has a main function. If someone knows what's wrong, or point me in the right direction, I'd be eternally grateful. Already spent the whole day trying to figure this out, really hope I can start developing tomorrow. -
Django queryset.values(col) throws FieldError: Cannot resolve keyword 'col' into field
I have the following model: class Record(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=SET_NULL, null=True, related_name='%(class)s_requests_created') date = models.DateTimeField(default=now, blank=True) # Generic Relationship content_type = models.ForeignKey(ContentType, null=True, on_delete=SET_NULL) object_id = models.PositiveIntegerField() content_object=GenericForeignKey('content_type', 'object_id',) def __repr__(self): return f'Record {{ User: {self.user}, Resource: }}' class Meta: ordering = ('-date',) For records objects with content_object properly set, if I run: Record.objects.all().values('date', 'user', 'content_object') Then I get the following error: Cannot resolve keyword 'content_object' into field. Choices are: content_object, content_type, content_type_id, date, id, object_id, user, user_id The error doesn't make any sense! As per the error content_object is a valid choice, then why the error? If I run [each.content_object for each in Record.objects.all()], I get no issues and get the expected results. What am I doing wrong? -
How to get absolute path from which a request originated in Django
How do I get the absolute request URL from which a request originated? For example, let's say I have a login endpoint (/auth/login/) and frontend consumes this endpoint from a page with path (https://example.com/login). How do I get the frontend path from backend? I have tried request.META and I noticed two very helpful headers: HTTP_ORIGIN (which will return https://example.com) and PATH_INFO. But PATH_INFO contains the actual login endpoint (/auth/login/) and not the frontend path, so I can't just concatenate. How can I go about this?