Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How Can I Validate Two Fields from Two different models using Django forms
I have two Models (Product and Sales) and the two models have their respective django forms modeled accordingly. The Product Model has a field named price while the Sales Model has a field named sellingprice. In my Validation rule I want to validated these two fields from two different models (Product and Sales) during user submission on one Django form. I want to check if the Product price is not less than or equal to the sellingprice of the Sales Model. Below is what I am trying to do but getting errors. from django import forms from django.core.exceptions import ValidationError class SalesForm(forms.Form): class Meta: model = Product, Sales fiels = __all__ ... def clean(self): cleaned_data = super().clean() product_price= cleaned_data.get("product_price") selling_price= cleaned_data.get("selling_price") if selling_price > product_price: # Only do something if both fields are valid so far. else: raise ValidationError( "Selling Price can not be less than or equal to Product Price " ) -
ModuleNotFoundError: No module named 'rest_framework' when running celery -A backend worker -l info
I'm trying to run my tasks and I'm currently using Celery for this alongside Django and DjangoRestFramework This is how I've set things up, root directory is also called backend . ├── backend │ ├── asgi.py │ ├── celery.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py └── save_to_db ├── admin.py ├── apps.py ├── dump.rdb ├── migrations │ ├── 0001_initial.py │ └── 0002_auto_20210728_0251.py ├── models.py ├── serializers.py ├── tasks.py ├── tests.py ├── urls.py └── views.py So I have all my configuration for Celery in celery.py which I followed from this on how to set up Celery for Django https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html This is how my config looks like import os from celery import Celery # Set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend.settings') app = Celery('backend') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django apps. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') I decided to run this command to get Celery started celery -A backend worker -l info But … -
Django: sql works well in mysql but gives error in cursor.execute
put sql sentence in sqlyog SELECT `v` ,`t` FROM `pm` WHERE `id`='12'; the true return is: v t ------- ------------- 13.32 23 13.319 23 13.319 23 but when I use cursor.execute() in django, it only returns one result and my code in django is: sql = "select v,t from pm where id = '12'" cursor = connection.cursor() cursor.execute(sql) V = cursor.fetchall() print(V) return result: ((13.319, 23.0),) if I use fetchone(),it will return one tuple ((13.319, 23.0)) This problem is really strange, and I hope that somebody can give me some hints. THANK YOU SOOOO MUCH! -
why django email message attach file use .file.name not .url?
In my django project: email.attach_file(self.object.pic.url) --> error no such file email.attach_file(self.object.pic.file.name) --> ok It make me confusing. -
Does a signal from a Parent model trigger when a child model is changed?
I've developed a custom library to sync some models. So, there is a Parent Model, called SyncModel on this library that has some child on my Django app. In this library, there is a receiver function to activate when someone makes a delete. Here is the function: @receiver(post_delete) def on_object_deletion(sender, instance, **kwargs): """Upload deleted object to cloud if it is part of synced model""" deletion_time = datetime.datetime.now() # Retrieve the metadata (app and model name) for the model contenttype = ContentType.objects.get_for_model(model=instance) # Skip unnecessary database lookup (never syncs its own models) if contenttype.app_label == "lakehouse_sync": return syncmodel = SyncModel.try_retrieve_model(contenttype.app_label, contenttype.model) if not syncmodel: return # Raise exception if the instance is not BaseSyncModel. # Should be caught during clean() though. if not isinstance(instance, BaseSyncModel): raise Exception("Cannot sync a model that does not inherit BaseSyncModel") # Manually update the timestamp so the lakehouse can merge data instance.updated_at = deletion_time # Write the serialized object to the cloud blacklist = syncmodel.get_blacklist() serialized = Serializer.serialize_object(instance, blacklist) CloudActions.write_delete_file( contenttype.app_label, contenttype.model, serialized.getvalue() ) And, in the apps.py file I added this receiver: def ready(self): """Import signals""" from lakehouse_sync.core import delete_action post_delete.connect(delete_action, sender=SyncModel, dispatch_uid=model.__name__) print('deleting') for model in SyncModel.__subclasses__(): post_delete.connect(delete_action, sender=model, dispatch_uid=model.__name__) My problem is related … -
No route matches the given query
I am having trouble loading my page as I am getting a 'Page Not Found' error that states 'no route matches the given query'. I believe this has to do with the first line in my views.py where I get the search variable. When I take out the search variable it says that it returns multiple routes (which I do have in my Django admin panel) but I am unsure how to change this so it could load the page and request? urls.py urlpatterns = [ path('', calc_distance, name='calc_distance') ] views.py def calc_distance(request): search = get_object_or_404(Route, id=1) form = DistanceMeasureForm(request.POST or None) geolocator = Nominatim(user_agent='distance') ip = '72.80.77.214' city, country, long_lat = use_ip(ip) latitude = long_lat.get('latitude') longitude = long_lat.get('longitude') city = long_lat.get('city') location = geolocator.geocode(city) print(location) l_lat = latitude l_long = longitude start = (l_lat, l_long) if form.is_valid(): lookup = form.save(commit=False) arrival_location = form.cleaned_data.get('arrival_location') arrival = geolocator.geocode(arrival_location) # print(arrival) end_latitude = arrival.latitude end_longitude = arrival.longitude end = (end_latitude, end_longitude) distance = geodesic(start, end).km lookup.location = location lookup.distance = distance lookup.save() context = { 'form': form, 'search': search } return render(request, 'home.html', context) Models.py class Route(models.Model): location = models.CharField(max_length=200) arrival_location = models.CharField(max_length=200) distance = models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(auto_now_add=True) def __str__(self): … -
I want to create a counter that filters out uploaded videos into different categories with different time filters (daily/weekly/monthly) any idea how
So I am trying to develop a web app and there's this part of project where I need to provide a counter that displays the number of videos uploaded and its corresponding status of the videos uploaded such as (Succesfully uploaded,uploading, pending upload, failed upload etc.). I also need to filter it into dates such as (daily/weekly/monthly) stats. Im using python and django on ubuntu and Im kinda new on it any idea how? -
Database query not working for Heroku deployment of Django/Python Project
I am deploying a Django project on Heroku. The deployment is successful and most functions of my web app are running just fine. However, I am having an issue with a single database query that seems not to work correctly on Heroku but works just fine on localhost. I am using this url_pattern: path('category/<str:cats>/', CategoryView, name='category'), Then in my views, I am running this queryset filter in my CategoryView: def CategoryView(request, cats): category_articles = Article.objects.filter(category=cats.replace('-', ' ')) return render(request, 'category.html', {'cats': cats.title().replace('-', ' '), 'category_articles': category_articles}) I don't have a Category Model. Instead, I am using forms.py to run category choices as follows: CATEGORY_CHOICES = ( ('Politics', 'Politics'), ('Business', 'Business'), ('Updates', 'Updates'), ('Education', 'Education'), ) class ArticleForm(forms.ModelForm): class Meta: model = Article fields = ('article_image', 'author', 'title', 'category', 'body') widgets = { 'article_image': forms.ClearableFileInput(attrs={'class': 'form-control'}), 'author': forms.Select(attrs={'class': 'form-control'}), 'title':forms.TextInput(attrs={'class': 'form-control'}), 'category': forms.Select(choices=CATEGORY_CHOICES, attrs={'class':'form-control'}), 'body': forms.Textarea(attrs={'class':'form-control',}), The following is my Article Model: class Article(models.Model): article_image = models.ImageField(null=True, blank=True, upload_to="images/") author = models.ForeignKey(User, null=False, blank=False, on_delete=models.CASCADE) title = models.CharField(max_length=100) category = models.CharField(max_length=40) body = models.TextField() def __str__(self): return self.name The html form has the select option for the choices provided. Once selected, an option is stored in the database when the user … -
Issue with creating a new object with a form (Django)
I am using the Django framework to build a website. This website is user based and each user has a profile model. Right now, I am working on building a system where each user can input their job experience. I want it so that you can input a category, and then fill out points for each category. (For example, if you wrote for the New York Times, the category would be "New York Times" and then right under it would be the articles you wrote in bullet points). I am at the stage where I am simply trying to make it so that the user can create a new category. I have an edit profile page where the user can already edit some details from the models. I tried to add on a form that creates a new category. When you submit the category, a success message dispays but when I look at my admin panel it doesn't create the object under categories. Here is the code: (Note: this form lets you choose the user for the category, I have to change it later to make it so that the category gets set to the user thats currently logged in) … -
if object exists in custom tag Django
This is my custom tag to show facebook link @register.simple_tag def facebook_link(): if Facebook.objects.first(): return str(Facebook.objects.first().link) else: return '' I want to show a block of html if object exists, tried to do as follows but it still displays the block {% if facebook_link %} html goes here {% endif %} any idea how to do it -
uWSGI not detecting Pipenv virtual environment
I'm using uWSGI on a Ubuntu 20.04 to host my Django API. This is my uwsgi.ini file: [uwsgi] #socket = :5000 socket = /home/ubuntu/lyrics-chords/lyrics-chords.sock chown-socket = ubuntu:www-data uid=ubuntu gid=www-data chmod-socket=660 master=true chdir = /home/ubuntu/lyrics-chords module = backend.wsgi:application virtualenv = /home/ubuntu/.local/share/virtualenvs/lyrics-chords-xEtMg5XN vacuum = true When I run uwsgi --ini uwsgi.ini outside of the virtual environment, the logs indicate that the virtual environment is not activated (or at the very least, that the modules in the virtual environment are not available). Here are the logs: *** Starting uWSGI 2.0.19.1 (64bit) on [Tue Aug 17 23:30:58 2021] *** compiled with version: 9.3.0 on 08 August 2021 17:51:00 os: Linux-5.8.0-1037-oracle #38~20.04.1-Ubuntu SMP Fri Jul 16 00:56:44 UTC 2021 nodename: lyrics-chords machine: aarch64 clock source: unix detected number of CPU cores: 1 current working directory: /etc/uwsgi/sites detected binary path: /home/ubuntu/.local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! chdir() to /home/ubuntu/lyrics-chords your processes number limit is 22953 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uwsgi socket 0 bound to UNIX address /home/ubuntu/lyrics-chords/lyrics-chords.sock fd 3 Python version: 3.8.10 (default, Jun 2 2021, 10:49:15) [GCC … -
Model class robovise.models.RoboProcessedFiles doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS Celery
I am using celery in my django project. 2 issues, the autodiscover task doesn't discover my task under robovise/tasks.py so I had to explicitly pass the path of the tasks file in the include argument of Celery instance. Then when I try calling the task in my django shell I get this error in Celery: [2021-08-17 16:26:36,312: ERROR/MainProcess] Task robovise.tasks.process_new_users_resp[5763be00-77d4-4705-bb9a-6e06f2b03464] raised unexpected: RuntimeError("Model class robovise.models.RoboProcessedFiles doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.") Traceback (most recent call last): File "/Users/cyzanfar/Desktop/beagle/projects/financial_services/env/lib/python3.8/site-packages/celery/app/trace.py", line 450, in trace_task R = retval = fun(*args, **kwargs) File "/Users/cyzanfar/Desktop/beagle/projects/financial_services/env/lib/python3.8/site-packages/celery/app/trace.py", line 731, in __protected_call__ return self.run(*args, **kwargs) File "/Users/cyzanfar/Desktop/beagle/projects/financial_services/financial_services/robovise/tasks.py", line 5, in process_new_users_resp from robovise.models import RegisteredUser File "/Users/cyzanfar/Desktop/beagle/projects/financial_services/financial_services/robovise/models.py", line 12, in <module> class RoboProcessedFiles(models.Model): File "/Users/cyzanfar/Desktop/beagle/projects/financial_services/env/lib/python3.8/site-packages/django/db/models/base.py", line 113, in __new__ raise RuntimeError( RuntimeError: Model class robovise.models.RoboProcessedFiles doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I've seen many post talking about this issue but have not found any solution. It's really strange as I have the same setup in another project and it works fine. project structure: ├── financial_services │ ├── __init__.py │ ├── asgi.py │ ├── celery.py │ ├── settings │ │ ├── __init__.py │ │ ├── base.py │ … -
Django and React push rejected, failed to compile on Heroku
I have been trying to deploy my Django and React application on Heroku in vain. The Django and React integration have been done by following more or less this guide: https://www.fusionbox.com/blog/detail/create-react-app-and-django/624/ The React app setting in settings.py: STATIC_URL = '/static/' REACT_APP_DIR = os.path.join(BASE_DIR, 'frontend') STATICFILES_DIRS = ( os.path.join(REACT_APP_DIR, 'build', 'static'), ) STATIC_ROOT = 'static/' My urls.py: from django.urls import re_path, path from backend.views import FrontendAppView urlpatterns = [ re_path('', FrontendAppView.as_view(), name='home'), ] My view: class FrontendAppView(View): """ Serves the compiled frontend entry point (only works if you have run `yarn run build`). """ def get(self, request): print(os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')) try: with open( os.path.join(settings.REACT_APP_DIR, 'build', 'index.html')) as f: return HttpResponse(f.read()) except FileNotFoundError: logging.exception('Production build of app not found') return HttpResponse( """ This URL is only used when you have built the production version of the app. Visit http://localhost:3000/ instead, or run `yarn run build` to test the production version. """, status=501, ) The error I am having. The Error is coming probably from this FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_79d83787/frontend/build/static' If yes then my question is why it is looking for '/tmp/build_79d83787/frontend/build/static'? if no, then what is the problem then. -----> Building on the Heroku-20 stack -----> Using … -
Django - Custom Cross Join fails due to expected join fields for on clause
I've created a custom class for implementing cross join's in Django using the following code class CrossJoinToFunction(Join): def __init__(self, table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation=None, table_function_params: List[Any] = None): super().__init__(table_name, parent_alias, table_alias, join_type, join_field, nullable, filtered_relation) self.table_function_params = table_function_params # type: List[Any] def as_sql(self, compiler, connection): sql, params = super().as_sql(compiler, connection) table_function_placeholders = [] table_function_params = [] for param in self.table_function_params: if hasattr(param, 'as_sql'): param_sql, param_params = param.as_sql(compiler, connection) else: param_sql = '%s' param_params = [param] table_function_placeholders.append(param_sql) table_function_params += param_params sql = '{} {}({}) {}'.format( self.join_type, compiler.quote_name_unless_alias(self.table_name), ', '.join(table_function_placeholders), self.table_alias ) return sql, table_function_params + params which can be used on custom Query as following self.alias_map[alias] = CrossJoinToFunction( join.table_name, join.parent_alias, join.table_alias, join.join_type, None, None, None, resolved_params ) The desired output in SQL from this is as follows select fb.id cf.some_returned_value from foobar fb cross join custom_function(params..) as cf The issue arrises with Django always expecting there to be a join_field for all joins. This conflicts with cross joins, as they do not have an on clause. Adding join.join_field throws to the CrossJoinToFunction raises the following django error self.alias_map[alias] = CrossJoinToFunction( join.table_name, join.parent_alias, join.table_alias, join.join_type, join.join_field, join.nullable, join.filtered_relation, resolved_params ) File "/Users/timmcgee/Documents/main-site/project/models.py", line 1493, in setup_joins join.table_name, join.parent_alias, join.table_alias, join.join_type, … -
Where should I set model fields derived from a form field?
Given a model with some fields which do not map directly to a ModelForm's fields, where should I set their value? In the following, form.blast_db should be assigned to either model.protein_db or model.nucleotide_db depending on what type of blast DB it is. They are mutually exclusive but required, so they must be set before model.full_clean() is called. from django.db import models class BlastQuery(models.Model): # Protein/nucleotide blast DB. Mutually exclusive, one must be provided protein_db = models.ForeignKey(ProteinDB, null=True, blank=True) nucleotide_db = models.ForeignKey(ProteinDB, null=True, blank=True) # Just 1 field to keep it terse but in reality there are many other fields foo = models.IntegerField() def clean(self): if self.protein_db and self.nucleotide_db: raise ValidationError('Protein/nucleotide DB are mutually exclusive') if not self.protein_db and not self.nucleotide_db: raise ValidationError('Protein/nucleotide DB are required') from django import forms class BlastForm(forms.ModelForm): # Magical field that's like a ModelChoiceField but can # hold both ProteinDB and NucleotideDB instances blast_db = BlastDBField() class Meta: model = BlastQuery fields = ('foo',) -
What is wrong with my upload CSV in Django?
I have created I think pretty standard code but the file seem not to get uploaded! My set up folder is empty plus no file displays after i click submit! When pressing submit I only see "GET /?csrfmiddlewaretoken=9JefYLkycrupVof72b1oujZ2DSi0o5BlfujkW27PhVDWBcoZyzc74aZ9yckOkJUz&myfile=file+.csv HTTP/1.1" 200 2844 and similar messages My code: Main project folder: In setting.py added MEDIA_URL = '/documents/' MEDIA_ROOT = os.path.join(BASE_DIR, 'documents') urlpatterns = [ ] if DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) url.py from django.contrib import admin from django.urls import path from django.conf.urls import include from mainsite import views as main urlpatterns = [ path('admin/', admin.site.urls), path('', main.model_form_upload, name= 'index'), path('contact/', include('contact.urls')), path('explanation/', include('modelexpl.urls')), path('uploads/', main.model_form_upload, name='model_form_upload') ] Then in my project folder: urls.py from django.shortcuts import render from django.http import HttpResponse from django.urls import path from mainsite import views # Create your views here. urlpatterns = [ path('', views.index, name='index') ] models.py from django.db import models # Create your models here. class Document(models.Model): description = models.CharField(max_length=200, blank= True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) views.py: initially I added following function: from django.shortcuts import render from django.http import HttpResponse from mainsite.models import Document from mainsite.forms import DocumentForm from django.core.files.storage import FileSystemStorage # Create your views here. def index (request): placeholder = {'test' : … -
Change instance values after capture change with Django Signals
I have a model Course that have a ManyToMany relation with my CustomUser model: class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('Email Address'), unique=True) user_name = models.CharField(_('User Name'), max_length=150, unique=True) # and a lot of other fields and stuff class Course(models.Model): enrolled_users = models.ManyToManyField(CustomUser, related_name="enrolls", blank=True) previous_enrolled_users = models.ManyToManyField(CustomUser, related_name="previous_enrolls", blank=True) course_name = models.CharField(_("Course Name"), max_length=200) What I'm trying to implement is that whenever a user finishes a course (and so the user is removed from enrolled_users), my application stores this user in previous_enrolled_users, so I can know the users that were previously enrolled at that course. I've implement a m2m_changed signal listening like this: def listen_m2mchange(sender, instance, model, pk_set, action, **kwargs): if action == 'pre_remove': # I'm trying to guess what to do m2m_changed.connect(listen_m2mchange, sender=Course.enrolled_users.through) With that, whenever I remove a user from a course, Django signals the m2m_changed and I capture that signal. I know that instance is the instance of the Course class and that model is the instance of that CustomUser class I'm removing. What I could not guess is how, using the instance of Course class, I can add the CustomUser in the previous_enrolled_users. Any help will be very appreciated. -
pipenv updates all dependencies bringing breaking changes
I'm having problems with an app that uses Django. Everything is in a docker container, there is a pipfile and a pipfile.lock. So far, so good. The problem is when I want to install a new depedency. I open the docker container shell, and I install the dependency with pipenv install <package-name>. After installing the package, pipenv runs a command to update the pipfile.lock file and doing so updates all packages to their last version, bringing whit these updates a lot of breaking changes. I don't understand why is this happening, I have all packages listed in my pipfile with ~=, this is suppose to avoid updating to versions that can break your app. I'll give you an example, I have this dependency in my pipfile: dj-stripe = "~=2.4". But, in the pipfile.lock file, after pipenv runs the command lock, that depedency is updated to its last version (2.5.1). What am I doing wrong? -
Django rest framework: exclude results when nested serializer is empty
I have a nested serializer that works, but I would like to exclude instances where the nested serializer is empty. The filtering I'm using on the nested serializer works, but currently this code returns all Sites, most of which have empty site_observations arrays when filters are applied. I would like to return only Sites that contain site_observations. I have tried a SerializerMethodField for site_observations but have the same issue. Using DRF 3.12 Relevant models are Site, and Observation which has FK to site, with related field=site_observations serializers.py class FilteredObsListSerializer(serializers.ListSerializer): def to_representation(self, data): projName = self.context["projName"] # this is my filter which works data = filter_site_observations(data, self.context["request"], projName) return super(FilteredObsListSerializer, self).to_representation(data) class ObsFilterSerializer(serializers.ModelSerializer): class Meta: list_serializer_class = FilteredObsListSerializer model = Observation fields = "__all__" class SiteSerializer(GeoFeatureModelSerializer): site_observations = ObsFilterSerializer(many=True) class Meta: model = Site geo_field = "geometry" fields = ("id", "name", "geometry", "site_observations") views.py class SiteList(generics.ListAPIView): queryset = Site.objects.all().order_by("pk") serializer_class = SiteSerializer # this is for filtering Observations on segment of an url: def get_serializer_context(self): context = super(SiteList, self).get_serializer_context() context.update({"projName": self.kwargs["name"]}) return context How can I exclude Sites where site_observations is an empty list? Thanks. -
Django and Ajax: add to Favourites button in a for loop functioning and making changes to database but not changing colour/name appropriately
I'm having difficulty understanding why my favourite buttons will not change colour and name when clicked to match the data in the database. I presume it is due to the way I have set up the 'is_fav' boolean variable but I've been unable to work out a fix. Any help is greatly appreciated! the view: def favourite_unfavourite(request): html = None #if request.method == 'POST': activity_id = request.POST.get('activity_id') activity = get_object_or_404(TherapyActivity, id=activity_id) #is_fav = False if activity.favourites.filter(id=request.user.id).exists(): activity.favourites.remove(request.user) is_fav = False else: activity.favourites.add(request.user) is_fav = True context = { 'Activity': activity, 'is_fav': is_fav, 'value': activity_id } if request.is_ajax(): html = render_to_string('main/favourite_section.html', context, request=request) return JsonResponse({'form': html}) page html: {% extends "main/index.html" %} {% block title %} <h1>View All</h1> {% endblock %} {% block content %} {% for activity in activities %} <div class="col-md-7 d-flex justify-content-between"> <li><a href="{{activity.get_absolute_url}}">{{activity.name}}</a> <br> {{activity.description}} </li> <div id="favourite-section"> {% include 'main/favourite_section.html' with activity=activity %} </div> </div> {% endfor %} {% endblock %} included section: {% if request.user.is_authenticated %} <form action="{% url 'account:favourite_unfavourite' %}" method="post"> {% csrf_token %} {% if fav %} <button type="submit" id="favourite" name="activity_id" value="{{ activity.id }}" class="btn btn-danger">Unfavourite</button> {% else %} <button type="submit" id="favourite" name="activity_id" value="{{ activity.id }}" class="btn btn-primary">Favourite</button> {% endif %} </form> {% … -
Heroku deploy with django database issue
i need some, did lot of research but cant find the solution. i just deployed my app into heroku, everything seem to work just fin, but the cant access to the database from the APP, admin looks empty. But the database is there on heroku when i check it database in heroku Settings.py Whitenoise whitenoise 2 database conection static urls.py static in URL i think maybe some config with the connection is missing, but i dont know what else to do... thanks in advanced for any help! -
Making API calls for authentication tasks in Angular
I'm trying to build an authentication system using Django, Django rest framework, angular, and I have been based on Dj-rest-auth to handle user registration and authentication tasks. I finished implementing the back-end level, but I'm getting stuck on how can I make API calls to register new users, log in as an authenticated user, and other queries such as forgot password, and email confirmation. Would you please help me to implement that in service.ts? -
Problem installing Pandas and Numpy on Heroku
I am trying to install Django 3.0.5 on heroku with numpy==1.18.3and pandas==1.0.3 libraries included in the requirements.txt file but it keeps running into an error. I have python-3.7.10 in my runtime.txt I ran the install command, but it gives me the following errors. git push heroku main and I am getting this error: Counting objects: 100% (107/107), done. Delta compression using up to 12 threads Compressing objects: 100% (95/95), done. Writing objects: 100% (107/107), 223.74 KiB | 6.99 MiB/s, done. Total 107 (delta 19), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Determining which buildpack to use for this app remote: -----> Python app detected remote: -----> No Python version was specified. Using the buildpack default: python-3.9.6 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Installing python-3.9.6 remote: -----> Installing pip 20.2.4, setuptools 47.1.1 and wheel 0.36.2 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting asgiref==3.2.7 remote: Downloading asgiref-3.2.7-py2.py3-none-any.whl (19 kB) remote: Collecting certifi==2020.4.5.1 remote: Downloading certifi-2020.4.5.1-py2.py3-none-any.whl (157 kB) remote: Collecting chardet==3.0.4 remote: Downloading chardet-3.0.4-py2.py3-none-any.whl (133 kB) remote: Collecting coverage==5.5 remote: Downloading coverage-5.5-cp39-cp39-manylinux2010_x86_64.whl (243 kB) remote: Collecting Django==3.1.12 … -
Is Mysql good for Django?
Do you think I can use MySql with Django, cuz a friend tells me it's not the best choice to use with Django framework -
Getting CSV saving in the document folder
I know this question probably appeared million times, but I cannot get my code to work. I want to upload csv to a folder, so I can make further operations on it. I think the problem might be in my HTML code, but not sure where. Folder I want to save it to is documents/, I did not add it to settings.py but I saw other people were not adding it there either. My code is as per below: Main urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from mainsite import views as main urlpatterns = [ path('admin/', admin.site.urls), path('', main.index, name= 'index'), path('contact/', include('contact.urls')), path('explanation/', include('modelexpl.urls')), path('uploads/', main.model_form_upload, name='model_form_upload') ] App urls.py from django.shortcuts import render from django.http import HttpResponse from django.urls import path from mainsite import views # Create your views here. urlpatterns = [ path('', views.index, name='index') ] App's models. from django.db import models # Create your models here. class Document(models.Model): description = models.CharField(max_length=200, blank= True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateTimeField(auto_now_add=True) App's views from django.shortcuts import render from django.http import HttpResponse from mainsite.models import Document from mainsite.forms import DocumentForm # Create your views here. def index (request): placeholder = {'test' : …