Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Porting and existing nested set hierarchy
I have a nested set category table developed with the PHP ORM Doctrine and I would like to port it to a Django app. I started porting it to django-treebeard, but I am having difficulties and I am not sure it can work. The original table had the needed fields lft, rgt and depth, so I added the tree_id field. I also had a foreign key to Accounts with one tree/account. Thus the table hold multiple independent trees that are not under a common root, with the lft and depth columns starting at 1 for each tree. So basically one nested set for each account in the table. I can add nodes to a tree just fine, but when I call the get_last_child method, I get nodes from other accounts. Does anyone know if there is a way to use treebeard, mptt or any other package without having to restructure the trees? -
Should I use the built-in admin panel Django? [closed]
There are html templates for the admin panel and personal profile of the site. Do I need to customize the built-in admin panel or is it better to use templates separately? -
Django REST Framework, setting up Django Storages/S3 Boto to store some media files to the bucket, and some to local storage
I've setup Django Storages/S3 Boto to save user-uploaded files to the s3 bucket, with the settings bellow: # AWS Bucket access keys AWS_ACCESS_KEY_ID = 'id' AWS_SECRET_ACCESS_KEY = 'key' # AWS Bucket config stuff DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_STORAGE_BUCKET_NAME = 'bucketname' AWS_S3_REGION_NAME = 'us-east-1' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com/' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # Media file location MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/' How would i modify the storage settings/configuration so that i can save some user uploaded files to this S3 bucket, while saving some others to the local file system? Currently, my FileField looks like this: class File(models.Model): created_at = models.DateTimeField(auto_now_add=True) email = models.EmailField(default='email@email.com') file = models.FileField(upload_to=upload_path) def __str__(self): return self.email + '-' + self.file.name my "upload_path" looks like this: def upload_path(instance, filename): return instance.email + '/' + filename -
django.core.exceptions.ImproperlyConfigured: The database name '****.amazonaws.com' (85 characters) is longer than PostgreSQL's limit of 63 characters
I am trying to migrate my Django model to the AWS Lightsail database, but I am getting below error. My database is on AWS Lightsail. it is PostgreSQL. I am deploying my project on AWS so I have set up almost everything except model migration. AMAZON DATABASE AVAILABLE CONNECTION OPTIONS: Endpoint-> ************.ap-******-1.***.amazonaws.com, Port-> 5444, User name-> db, Password-> Something MY SETTINGS.PY FILE DATABASE CONNECTION OPTIONS: 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '****Endpoint*****', 'USER': 'db', 'PASSWORD': 'Something', 'HOST': '5444' } } Terminal Error: > `2, in build_graph self.applied_migrations = recorder.applied_migrations() File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/migrations/recorder.py", lin e 76, in applied_migrations if self.has_table(): File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/migrations/recorder.py", lin e 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 260, in cursor return self._cursor() File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 236, in _cursor self.ensure_connection() File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 220, in ensure_connection self.connect() File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/utils/asyncio.py", line 26, in inner return func(*args, **kwargs) File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/backends/base/base.py", line 196, in connect conn_params = self.get_connection_params() File "/home/bitnami/portfolio/ManojJha-portfolio/.venv/lib/python3.7/site-packages/django/db/backends/postgresql/base.py" , line 165, in get_connection_params self.ops.max_name_length(), django.core.exceptions.ImproperlyConfigured: The database name '*****************Database End-point*****************.***.amazonaws.com' (85 characters) is longer than PostgreSQL's limit of 63 characters. Supply a shorter NAME in settings.DATABASES.``` So is there any … -
How to plug the reponse of a django view GET request into the same view as a POST request during testing?
I have a Django function-based form view that initializes a form with default data on a GET request, and saves the model object on a POST request: def copy(request, ann_id): new_ann = get_object_or_404(Announcement, pk=ann_id) new_ann.pk = None # autogen a new primary key (quest_id by default) new_ann.title = "Copy of " + new_ann.title new_ann.draft = True new_ann.datetime_released = new_ann.datetime_released + timedelta(days=7) form = AnnouncementForm(request.POST or None, instance=new_ann) if form.is_valid(): new_announcement = form.save(commit=False) new_announcement.author = request.user new_announcement.datetime_created = timezone.now() new_announcement.save() form.save() return redirect(new_announcement) context = { "title": "", "heading": "Copy an Announcement", "form": form, "submit_btn_value": "Create", } return render(request, "announcements/form.html", context) I can't figure out how to test the form.is_valid() branch when the form is posted, without manually providing the form data to self.client.post(url, form_data) in my view. What I want to actually test is that the result of the get provides valid default data for the form that can then be submitted via post request. But I can't figure out how to change the repsonses, so that the form data resulting form the get request is then fed into the form data provided to the post request. EDIT I found the location of the form in the get response, but … -
DJONGO - Querying Array fields with DateField filter
I have a model called GOALS it has a field of type "ArrayModelField". This field is a list of another model called GOAL, that has a Date type field, as shown below: from djongo import models class Goal(models.Model): date = models.DateField() daily_value = models.FloatField() hourly_values = models.ListField(default=[]) class Goals(models.Model): name = models.TextField(primary_key=True, null=False, blank=False) goals = models.ArrayModelField(model_container=Goal, default=[]) eu = models.TextField(null=True, blank=True) I am trying to filter my results by the fields in the inner model (GOAL), and I know it is possible because there are some examples in Djongo's documentation showing how to do it: class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() class Entry(models.Model): blog = models.EmbeddedField( model_container=Blog, model_form_class=BlogForm ) headline = models.CharField(max_length=255) authors = models.ArrayField( model_container=Author, model_form_class=AuthorForm ) entries = Entry.objects.filter(authors={'name': 'Paul'}) Or even looking at an specific array position, like so: entries = Entry.objects.filter(authors={'2.name': 'Paul'}) But in my case, I want to go a little further, I want to filter by a specific YEAR in my DateField. In DJANGO would be something like this: Goals.objects.filter(date__year='2011') I wonder... is there something similar in DJONGO? Maybe something in these lines? Goals.objects.filter(goals={'date__year': '2020'}) -
RelatedObjectDoesNotExist at /post/new/ - Post has no author
I have implemented allauth for user registration and now I am trying to associate the current_user to a post when its being created. When I press 'Submit' I get 'Post has no author' clearly the posts don't recognize the user. Model: from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.DO_NOTHING) def __str__(self): return self.title View: def create_post(request, pk=None): form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author(request.user) post.save() else: form = PostForm() context = {'form' : form} return render(request, 'blog/create_post.html', context) I could really use some pointers, many thanks. -
Django - query all records matching current logged in user
I'm struggling to understand how to format queries in views - especially in regards to the current logged in user. I would like to display all books whose user_added value matches the current logged in user's ID. models.py class books(models.Model): user_added = models.ForeignKey(User, default='1', on_delete=models.CASCADE) title = models.CharField(max_length=100) i'm using Django's Users model and functionality forms.py class books_list(forms.ModelForm): class Meta: model = books fields = ['user_added', 'title'] views.py class booksListView(ListView): def get_queryset(self): # id = ? -
problem in connecting html page with django
Whenever I try to connect my html webpage as a template as it shows the following error ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. my webapp.urls file looks like this from django.conf.urls import url from django.contrib import admin from . import views urlpatters=[ url(r'^admin/',admin.site.urls), url(r'^$',views.test), ]``` and my views file is ```from django.shortcuts import render def test(request): return render(request,"test.html") any help would be appreciated -
Django Model/Manager Dependency
When using a Custom Model Manager the way it is shown in the documentation and examples that I have found, the Custom Managers are placed in the same source file as the Model. My models.py file has a base class with four sub-classes and the base class has several static methods to provide some common queries. I will need to add quite a few custom queries. I would prefer to put these in a Custom Model Manager that is a Base class for each of the subclasses Model Managers. I would also like to be able to separate the Model Managers into a separate source file called managers.py to make the code less messy. The problem is that there is a cyclic dependency between the Models and Managers. Is there a way to set the Manager to the "objects" variable by name instead of the actual Model Manager class? Or perhaps some other way to be able to put the code into the two separate files? models.py class MyBaseModelClass(models.Model): (abstract) class class SubclassA(MyBaseModelClass): objects = SubclassAManager() class class SubclassB(MyBaseModelClass): objects = SubclassBManager() class class SubclassC(MyBaseModelClass): objects = SubclassCManager() class class SubclassD(MyBaseModelClass): objects = SubclassDManager() managers.py class MyCustomBaseManager(models.Manager): # Does custom … -
Font-awesome Icons not loading after connecting to AWS
I am doing a project for developing a website. I chose Django for my backend. I have uploaded my static files on Amazon s3 bucket. All my CSS files and images and every static file are loading except the icons from font-awesome. I tried using their CDN. Yet no result. <link href="{% static 'vendor/fontawesome-free/css/all.min.css' %}" rel="stylesheet"> <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"> I see no results whatsoever. The URL of my website: https://fine-arts-club.herokuapp.com/ -
How to filter objects based on model fields in Django
I have a Model named Order that has a foreign key pointed to the current user class Order(models.Model): customer_name = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='customer_name', ) order_individual_price = models.IntegerField(default=1) order_default_price = models.IntegerField(default=1) order_name = models.CharField(max_length=200) order_quantity = models.IntegerField(default=1) order_total_price = models.IntegerField(default=1) I currently have 2 order objects from 2 different users. How would I filter the objects so that it only shows the one from a specific user? I currently have the following code: Order.objects.filter(customer_name='chironsus') It gives me this error: ValueError: Field 'id' expected a number but got 'chironsus'. -
Efficient way of finding out the individual country count of League matches and its points in points table Django
I got stuck with a Homework problem and don't have a clue for further steps. I have three models to handle the points table like Match, Score, Pointstable. I'm handling the fixtures in the Match Model. And scores of Team1 and Team2 in Scores Model with their scores. and Finally, a points table as below. I have created a points table Template to handle the same which consists of Matches for an individual country, won, Loss, Points Models class Match(models.Model): Bat_Bowl =(('Bat', 'Bat'), ('Bat', 'Bowl')) clubstate = models.ForeignKey('Clubstate', on_delete=models.CASCADE, default=0) date = models.DateTimeField(default=datetime.now, blank= False) ground = models.CharField(max_length=100) Team1 = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, related_name='team1',default = 0) Team2 = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, related_name='team2',default = 0) Team1logo= models.ImageField(upload_to='images/', verbose_name = 'Team1 logo',default = 0) Team2logo= models.ImageField(upload_to='images/', verbose_name ='Team2 logo',default =0) League = models.CharField(max_length=100, default = 0) Toss_won_by = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, related_name='tosswon',default = 0) Elected_to = models.CharField(max_length=100,choices=Bat_Bowl) def __str__(self): return str(self.Team1) + ' vs ' + str(self.Team2) + ' Dated on ' + str(self.date.date()) +' at ' + str(self.ground) def toss_won(self): return 'Toss Won by ' + str(self.Toss_won_by) + ' and elected to ' + str(self.Elected_to) + ' first' class Score(models.Model): matches_between = models.ForeignKey('Match',on_delete = models.CASCADE, related_name ='fixture_between') Team1 = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, related_name='teamA',default = 0) … -
Model not declaring an explicit app_label in Django model
I have a basic Django app that I am trying to build out and test the model on via the Python interpreter. I believe there is something wrong with my models.py file but I'm not sure what, I'm running through a tutorial from the Django website and am trying to build my app in line with that. Running the migration went fine but when I run: from news.models import Author, Article, Source I get this error: Traceback (most recent call last): File "/usr/lib/python3.6/code.py", line 91, in runcode exec(code, self.locals) File "<input>", line 1, in <module> File "/snap/pycharm-professional/196/plugins/python/helpers/pydev/_pydev_bundle/pydev_import_hook.py", line 21, in do_import module = self._system_import(name, *args, **kwargs) File "/home/etherk1ll/Development/python_projects/NewSite/news/models.py", line 6, in <module> class Author(models.Model): File "/usr/local/lib/python3.6/dist-packages/django/db/models/base.py", line 115, in __new__ "INSTALLED_APPS." % (module, name) RuntimeError: Model class news.models.Author doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. The model in located in my news app as and my installed INSTALLED_APPS has the 'news.apps.NewsConfig' present in settings.py. INSTALLED_APPS = [ 'news.apps.NewsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] news/model.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models class Author(models.Model): name = models.CharField(max_length=50) class Article(models.Model): authors = models.ManyToManyField(Author) # title = models.CharField(max_length=200) description = … -
specify submit button when testing a form view in Django
I'm trying to test a django form view: form_data = { 'comment_text': "test comment" } response = self.client.post(reverse('announcements:comment', args=[self.test_announcement.id]), form_data) self.assertEqual(response.status_code, 404) # invalid submit button But my views checks to see what button was used to submit the form with: if 'comment_button' in request.POST: # process form else: raise Http404 How can I mimic the 'comment_button' being used to submit the form in my test? -
Django Ajax form not submitting and page freezes
I am trying to submit a form using Ajax, however, after I press submit I can see that my view is called successfully in the terminal but the success message is not getting printed and the page freezes. I assume my ajax call is getting stuck. my form is: <form method="POST" data-url="{% url 'home:post-detail' guid_url %}" class="post-comment-form" style="height: 1rem;"> {% csrf_token %} <div class="input-group"> {{ form }} <div class="input-group-append"> <button class="btn btn-sm small btn-outline-primary ml-1" style="height: 2.3rem; border-radius: 20px; text-decoration: none;" type="submit">Add</button> </div> </div> </form> my ajax function is: $(document).on('submit','.post-comment-form', function (e) { console.log($(this).serialize()); form = $(this).serialize(); e.preventDefault(); $.ajax({ url: $(this).attr('data-url'), type: $(this).attr('method'), data: form, dataType: 'json', success: function(response) { $("#post-linked-comments div").html(response['html']); console.log("successfully submitted form") $('textarea').val(''); $('.reply-btn').on("click", function () { $("#modal-comment-reply textarea").attr("placeholder","Add your reply") $("#modal-comment-reply textarea").addClass("comment-reply-adjust") var c_id = $(this).data('id'); $("#c-get-id").val(c_id); $('textarea').val(''); $("#modal-comment-reply").modal("show"); }); $('.view-replies').on('click', function () { var h = $(this).data('hidden'); var curr = $(this).text() var newt = $(this).attr('text') $(this).text(newt) $(this).attr("text",curr) var id = $(this).data('id'); if(h == 1){ $("#c-"+id).show(); $(this).data('hidden',0); } else { $("#c-"+id).hide(); $(this).data('hidden',1); } }); }, error: function(rs, e){ console.log(rs.responeText); }, }); }); I have already tried: $('.post-comment-form').on('submit', function (e) {}); my view for handling the function is: @login_required def post_detail(request, guid_url): data = dict() post = … -
Django Queryset in template
So the thing is I have this Django ORM QuerySet to get all the Projects and their respective xpm and I just can't figure out why it won't output any of the xpmNumber in the template. xpms = Project.objects.values(ProjectName=F('description'), xPM=F('p_set__flexPMNumber')) I also got this other function to retrieve the same thing but using arawquery: def get_pms(): with connection.cursor() as cursor: cursor.execute('SELECT p.Id, f.Id, p.description AS ProjectName, f.xPMNumber AS xPM FROM ' 'project_project p LEFT OUTER JOIN xpm_pm f ON f.ProjectID = p.Id') xpms = cursor.fetchall() return xpms xpms = get_pms() And this is the template code where I'm trying to render it <div class = "list-group"> {% for f in flexpms %} <a href="" class="list-group-item list-group-item-action"> <p>{{ f.description }}</p> </a> {% endfor %} </div> I've tried with {{ f.projectId.xpmNumber }} to iterate over the first queryset but I get nothing back, I did check that the database has info in those tables and it does. I've also tried to retrieve all the xpms and then use the projectId foreign key like this: xpms = xPMs.objects.all() and iterate over it like this: { % for f in xpms %} {{ f.projectId.description }} {{ f.xPMNumber }} How do I render those xPMNumbers … -
How do translate django template parts?
I've some templates for header and footer html on my templates folder on the root of my project, but the translation is not working with the .mo file, it looks like the translation only occurs on "simple" words like "Home" but the words that i've translated in .po files does not show up. settings: MIDDLEWARES = { # ... 'django.middleware.common.CommonMiddleware', 'django.middleware.locale.LocaleMiddleware', # ... } USE_I18N = True LANGUAGE_CODE = 'en' On my templates/header.html: {% load i18n %} <h1>{% trans "Home" %}</h1> <h1>{% trans "RESOURCES" %}</h1> The locale file on locale/pt-br/LC_MESSAGES #: templates/homepage-navbar.html:21 msgid "RESOURCES" msgstr "RECURSOS" #: templates/homepage-navbar.html:18 msgid "Home" msgstr "Inicio" The template slice is imported on the package example/templates/example/index.html {% include 'homepage-navbar.html' %} But the template only translate "Home" to Início (it's not even what i translate) and it does not translate RESOURCES -
remove orphaned file from a model
I have the following model: class Class(models.Model): title = models.CharField(max_length = 60) video = models.FileField( upload_to = class_files_custom_upload, validators = [ FileExtensionValidator(['mp4', 'webm', 'mpg', 'mpeg', 'ogv']), ] ) section = models.ForeignKey(Section, on_delete = models.CASCADE) created = models.DateTimeField(auto_now_add = True) class Meta: verbose_name = 'clase' verbose_name_plural = 'clases' ordering = ['created'] def __str__(self): return self.title I create an instance of this model, but if I update the video field with another file of any instance, the previous saved file is orphaned and the file takes up space and I want to avoid it, deleting the file. To do this I customize the file load, putting a callable in the upload_to: def class_files_custom_upload(instance, filename): try: old_instance = Class.objects.get(id = instance.id) old_instance.video.delete() except Class.DoesNotExist: pass return os.path.join('courses/videos', generate_secure_filename(filename)) In this way I achieve my goal. But I have several models that save multimedia files, and for each one I have to customize the file load, practically doing a function almost equal to class_files_custom_upload, and the code repeats and this is not optimal at all. I tried to create a reusable function that meets the goal of the class_files_custom_upload function, in various fields like ImageField and FileField, but I can't do it since the … -
Only one field in a Django ModelForm widgets is working
I have a ModelForm wherein the Meta class I say which fields I want and then try to edit the widgets for all of those fields but only the first field is actually working, when I go to the inspector only the first field has the modifications. Forms code: class UserSignUpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text="Please insert a valid email") class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] widgets = { 'username': forms.TextInput(attrs={'id': 'signup_username', 'placeholder': 'Username'}), 'email': forms.EmailInput(attrs={'id': 'signup_email', 'placeholder': 'Email'}), 'password1': forms.PasswordInput(attrs={'id': 'signup_password1', 'placeholder': 'Password'}), 'password2': forms.PasswordInput(attrs={'id': 'signup_password2', 'placeholder': 'Repeat Password'}) } Template Code: {% for field in signupForm %} {{ field }} {% endfor %} Inspector Code: <input type="text" name="username" id="signup_username" placeholder="Username" maxlength="150" autofocus required> <input type="email" name="email" maxlength="254" required id="id_email"> <input type="password" name="password1" autocomplete="new-password" required id="id_password1"> <input type="password" name="password2" autocomplete="new-password" required id="id_password2"> What am I doing wrong here? -
Django filter based on field of latest related model
I have a model Post and Comment and i'm trying to filter a list of posts to only show the ones that have a certain boolean value (here called epic_bool) on the latest comment. I am trying it as follows: object_list = Post.objects.all() newest = Comment.objects.filter( post=OuterRef('pk') ).order_by('-upload_date') Post.objects.annotate( is_true=Subquery(newest.values('epic_bool')[:1]) ) object_list = object_list.filter(is_true=True) But I get FieldError Cannot resolve keyword 'is_true' into field. Choices are: ... I don't understand why because i'm trying to annotate and not resolve a field!? -
error: 'ValueError: _names_ are reserved for future Enum use'
I'm deploying my Django project on a Linux server. When I run the command python manage.py collectstaticI get the following error: File "/home/student/PickFeel/venv/lib/python3.5/site-packages/django/db/models/enums.py", line 81, in TextChoices def _generate_next_value_(name, start, count, last_values): File "/usr/lib/python3.5/enum.py", line 61, in __setitem__ raise ValueError('_names_ are reserved for future Enum use') ValueError: _names_ are reserved for future Enum use enum.py is a system generated file. How do I fix this? -
Django TestCase and Transactions
I am running into a weird issue while writing unit tests that I think is related to this from the django docs - Django's TestCase class wraps each test in a transaction and rolls back that transaction after each test, in order to provide test isolation. This means that no transaction is ever actually committed, thus your on_commit() callbacks will never be run. My issue is occuring when working with update_fields in save(). Some pseudo code for example. object.is_processing = timezone.now() object.save(update_fields=['updated', 'is_processing']) try: with transaction.atomic(): # do stuff object.other_field = value object.save() finally: object.is_processing = None object.save(update_fields=['updated', 'is_processing']) Now when I run tests, it tries to create the object twice. Why? I think it is because this is all in a transaction, so the object is never actually committed to the database. When I call save with update_fields the pk is excluded, so it looks at it like a new object, and tries creating it twice. If I do the following, it works. object.is_processing = timezone.now() object.save() try: with transaction.atomic(): # do stuff object.other_field = value object.save() finally: object.is_processing = None object.save() What I am trying to figure out is how to test this without changing the production code … -
get host address heroku django API
I have deployed a react-django app on heroku.... The react front end makes calls to the django backend. However, django backend isn't accepting the requests..I'm guessing that it's either 1) wrong host address or 2) server didn't start... if it's wrong host address(' i used '127.0.0.1' as host address in all urls for get and post in react), how do i get the right one, else if server didn't start, how do i get it to start, else kindly point out the problem and the solution. What is the problem? Thanks to anyone trying to help : ) -
why this basic like implementation isn't working?
I'm making a simple like button but it's not working and I get the error database is locked and that's because sqlite can't handle it but I want to make a simple like button and if sqlite can't handle it then it's not simple. this is the like model: class Like(models.Model): username = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) imageid = models.CharField(max_length=50) and this is the view: @login_required def like(request, imageid, action): username = request.user im = get_object_or_404(Images, imageid=imageid) likecount = Like.objects.filter(imageid=imageid).filter(username=username).count() if likecount == 0: l = Like(username = username, imageid= imageid) l.save() if action == 'vote': im.vote = F('vote') + 1 im.save() else: return redirect('home') else: print("already liked") how can I make this work? thanks