Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to integrate video call and chat functionality in Django project?
i don't know whether i am violating the Stack Overflow guidelines but can anyone tell me who to integrate Video calling and Chatting functionality in a Django project. I don't want to create anything from scratch so how to use additional packages to accomplish this task? -
Django: what does new group, create mean?
I am trying to create different groups to be given different permission: new_group, created = Group.objects.get_or_create(name ='new_group') Came across this code and I just want to clarify what it means. This is my guess: I am creating a new group and that will be the name of that variable. But what does the ', created' mean? Then for the groups basically you just want to get a group and if there isnt a group you will create it. Thanks. -
django, admin jet- Problems with the same privileges of admin and staff
I designated admin menu through django-jet. settings.py JET_SIDE_MENU_ITEMS = [ { "label": _("board"), "app_label": "board", "items": [ {"name": "notice"}, {"name": "event"}, ], }, { "label": _("user"), "app_label": "users", "items": [ {"name": "user"}, {"name": "devices"}, {"name": "pushnotifications"}, {"name": "pushnotificationlogs"}, ], },] And then, I classified the member type as "manager" and called it [is_staff = true] I gave the manager access to the board app only. board_groups.py GROUPS_PERMISSIONS = { "Manager": { models.Notice: ["add", "change", "delete", "view"],} However, like the account in [super_admin], the account with the privileges of [is_staff] can see all models("label": _("board") &"label": _("user")) Is it because of the menus I prepared in the settings.py? -
How can i access to my application using IP I'm really tired
I'm working on a small project using Vue.js / Django Rest Framework I created my application, now I just want to visit my work, but I don't know which IP address I have to use in the browser to see my work, I tried everything this is my vue.config.js const BundleTracker = require("webpack-bundle-tracker"); module.exports = { publicPath: "http://0.0.0.0:8080/", outputDir: './dist/', chainWebpack: config => { config .plugin('BundleTracker') .use(BundleTracker, [{filename: './webpack-stats.json'}]) config.output .filename('bundle.js') config.optimization .splitChunks(false) config.resolve.alias .set('__STATIC__', 'static') config.devServer // the first 3 lines of the following code have been added to the configuration .public('http://127.0.0.1:8080') .host('127.0.0.1') .port(8080) .hotOnly(true) .watchOptions({poll: 1000}) .https(false) .disableHostCheck(true) .headers({"Access-Control-Allow-Origin": ["\*"]}) }, // uncomment before executing 'npm run build' // css: { // extract: { // filename: 'bundle.css', // chunkFilename: 'bundle.css', // }, // } }; I do npm run serve also I do python manage.py runserver / but when i access to the browser nothing is work -
Django app with gunicorn and container stack not running when deployed to heroku
I built a Django 3.1.0 app on my dev server (local windows machine) with postgreSQL, and I can run it perfectly well from inside a Docker container. When I deploy to heroku, I get no error, but when I click Open App (or run command heroku open -a myapp) it opens a browser window with a message as follows: Heroku | Welcome to your new app! Refer to the documentation if you need help deploying. I've tried several things, including running heroku ps which says 'no dynos on myapp'. Also tried running heroku ps:scale web=1 but to no effect. I have a Profile at the appropriate folder level, and it does not have a .txt or any other suffix. Also, it contains the following line: web: gunicorn config.wsgi --log-file - The stack is set to container on heroku. Another app deployed successfully but without using container. Another thing: when I run heroku run python manage.py migrate, or heroku run python manage.py createsuperuser, the commands seem to run forever and I have kill with CTRL-C. Not sure what's going on. Any help would be greatly appreciated. I've looked at a dozens similar threads here but my problem remains unresolved. Not sure … -
Django admin add view with custom actions (buttons)
I want to add in the admin, the possibility to approve or reject the registration of certain users. For that I want to add in the listing of these users a custom action that redirets to another view. In this other view I want to be able (as the admin) to check the info of the user and then either Approve or Reject the registration with two buttons. Having differentt logic for each choice. I've managed to the add the action in the listing, but can't seem to see the view. It automatically goes to the second step of approving. register.html {% extends "admin/base_site.html" %} {% block content %} <div id="content-main"> <form action="" method="POST"> {% csrf_token %} <fieldset class="module aligned"> {% for field in form %} <div class="form-row"> {{ field }} </div> {% endfor %} </fieldset> <div class="submit-row"> <input type="submit" class="default" value="Aprobar"> <input type="submit" class="default" value="Rechazar"> </div> </form> </div> {% endblock %} form.py class RegisterForm(forms.Form): def approve(self, student): pass def reject(self, student): pass def save(self, student): try: student.registered = True student.save() except Exception as e: error_message = str(e) self.add_error(None, error_message) raise return student admin.py @admin.register(PreRegisteredStudent) class StudentPreRegistered(StudentCommonAdmin): def check_button(self, obj): return format_html( '<a class="button" href="{}">Check</a>', reverse('check', args=[obj.pk]), ) actions = … -
Django restframework and markdownx
I want to know how to use preview of markdownx in restframework serializer. Example: I can show the preview by rendering the HTML with followings: {{form}} {{form.media}} However, Idk how to do it with {% render_form serializer %} Should i manually make a preview div in HTML and manually achieve it through ajax? -
Django Pagination Issues - Beginner
I'm making a project with Django and learning about pagination for the first time. I've read a lot of documentation so far but still can't get it to work. I don't know what I'm doing wrong. Any insight is helpful. From my understanding, this should make only 3 posts appear on the page. Instead, all of the posts appear. I want to make it so only 3 posts appear on the page at once. I don't get any errors with this. I just see all the posts on the page. views.py from .models import User, Post from django.core.paginator import Paginator def index(request): list_of_posts = Post.objects.all().order_by('id').reverse() paginator = Paginator(list_of_posts, 3) page_number = request.GET.get('page', 1) page_obj = paginator.get_page(page_number) return render(request, "network/index.html", { "list_of_posts": list_of_posts, "page_obj": page_obj }) Portion of the html for pagination: <div class="container"> <ul class="pagination justify-content-center"> {% if page_obj.has_previous %} <li class="page-item"><a href="?page=1" class="page-link">&laquo; First</a></li> <li class="page-item"><a href="?page={{ page_obj.previous_page_number }}" class="page-link">Previous</a></li> {% else %} <li class="page-item disabled"><a class="page-link">&laquo; First</a></li> <li class="page-item disabled"><a class="page-link">Previous</a></li> {% endif %} {% if page_obj.number %} <li class="page-item"><a class="page-link">{{ page_obj.number }}</a></li> {% else %} <li class="page-item"><a class="page-link">0</a></li> {% endif %} {% if page_obj.has_next %} <li class="page-item"><a href="?page={{ page_obj.next_page_number }}" class="page-link">Next</a></li> <li class="page-item"><a href="?page={{ page_obj.paginator.num_pages }}" class="page-link">Last … -
Performance difference of template logic vs. get_context_data
I am displaying a list of Bicycles. The Bicycle model has a function get_wheels that gets objects of type Wheel related to that model Bicycle instance. For each instance of Bicycle, I want to list all related Wheel objects in the template. Is it faster to call get_wheels in the get_context_data method, or is it faster to call get_wheels in the template? How I call it in the template: {% with wheels=p.get_wheels %} {% if files %} {% for w in wheels %} {{ w.store.label }} {% endfor %} {% endif %} {% endwith %} How I would call it in get_context_data: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) bicycles = context['object_list'] for bicycle in bicycles: wheels = bicycle.get_wheels() if wheels: test.wheels = wheels return context Kind of related to Iterate over model instance field names and values in template Disclaimer: I am using Bicycles and Wheels as examples, this is not my actual use case. But I do have a model one one type that has a class function that gets the related models of type B. The question is about the speed of getting data in the template rather than in get_context_data -
pyexcel save to Django model
Having difficulties understanding the documentation for interaction between dest_initializer and dest_model? If I have a Django model like: class MyModel(Model) file = FileField() How can I write a file to an instance of this model? instance = MyModel() records = [OrderedDict([("Test Key", "Test Value")])] pyexcel.save_as( records=records, dest_model=MyModel, ...... ?????? How to write to instance.field? ) -
TypeError at / 'NoneType' object is not callable
this is the code. kindly tell me what i'm doing wrong ... def allowed_users(allowed_roles=[]): def decorator(view_func): def wrapper_func(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group in allowed_roles: return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to view this page') return wrapper_func return decorator def admin_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.user.groups.all()[0].name if group == 'customer': return redirect('user-page') if group == 'admin': return view_func(request, *args, **kwargs) return wrapper_function -
static file loading problems on pythonanywhere
i'am trying to deploy restframework on pythonanywhere so i can use it in for my android project but the issues here that the restframework page is shown whitout a css or js files [enter image description here][1] [1]: https://i.stack.imgur.com/ImW94.png i tried evrey solution on stackoverflow but nothing work ! i collectstatic file using python manage.py collectstaticfile i set up `STATIC_ROOT='/home/ssmedicament/api/static/'` `STATIC_URL = '/static/'` -
How do I get FormSet to validate in my view?
I am doing something a bit unusual with FormSets. I am attempting to use a queryset as the input to my formset. This seems to be working at this point just fine. What isn't working is the form validation. Thanks in advance for any thoughts. I can't create this relationship via a traditional foreign key for reasons I won't bother people with. My Models.py class Team(models.Model): team_name = models.CharField(max_length=264,null=False,blank=False) class Player(models.Model): player_name = models.CharField(max_length=264,null=False,blank=False) team_pk = models.integerfield(Team,null=True,on_delete=models.CASCADE) My views.py class CreateTeamView(LoginRequiredMixin,UpdateView): model = Team form_class = CreateTeamForm template_name = 'create_team.html' def get_context_data(self, **kwargs): context = super(CreateTeamView, self).get_context_data(**kwargs) dropdown = self.request.GET.get("dropdown", None) queryset = Player.objects.filter(company_pk=dropdown) player_form = PlayerFormSet(queryset=queryset,dropdown=dropdown) context['player_form'] = player_form context['dropdown'] = dropdown return context def get_form_kwargs(self): kwargs = super(CreateTeamView,self).get_form_kwargs() kwargs['user'] = self.request.user kwargs['dropdown'] = self.request.GET.get("dropdown") return kwargs def get(self, request, *args, **kwargs): dropdown=self.request.GET.get("dropdown") self.object = self.get_object() context = self.get_context_data(object=self.object) self.object = None context = self.get_context_data(object=self.object) form_class = self.get_form_class() form = self.get_form(form_class) form_kwargs = self.get_form_kwargs() player_form = PlayerFormSet(dropdown=dropdown) return self.render_to_response( self.get_context_data(form=form, player_form=player_form, context=context, )) def form_valid(self, form, player_form): self.object = form.save() player_form.instance = self.object player_form.save() def form_invalid(self, form, player_form): return self.render_to_response( self.get_context_data(form=form, player_form=player_form, )) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) dropdown=self.request.GET.get("dropdown") player_form … -
Can I use a 6-digit pin code instead of password in logging in my users in django authentication?
Is there a way where the users can login to my webapp using their username and a 6-digit pin (like the ones we use in our atms) instead of using the password? I am new to django and don't know how or where to look in this. Thank you! -
Django URL path not matching
I am currently having a non-matching URL error for the following URL http://127.0.0.1:8000/report/?report=Report. The questions/answers found here and elsewhere have been of no use. I have a button that I am trying to redirect with. report/ ?report=Report [name='candidate-report'] The current path, report/, didn't match any of these. project.urls: from django.urls import include, path from . import views urlpatterns = [ path('', views.home_view, name='home'), path('report/', include('Reports.urls')) ] Reports.urls: from django.urls import path from . import views urlpatterns = [ path('?report=Report', views.candidate_report_view, name='candidate-report'), ] Reports.views: from django.shortcuts import render from .forms import CandidateReportForm def candidate_report_view(request): category_form = CandidateReportForm.category() comment_form = CandidateReportForm.comment() return render(request, 'candidate_report.html', {'category_form': category_form, 'comment_form': comment_form}) base.html: <form class="d-inline-block float-right" action="report/" method="get"> <input class="btn btn-primary" id="report_button" name="report" type="submit" value="Report"> -
Django channels error when attempting to serve static files with devserver
I moved my project into another environment and after installing the dependencies and attempting to run the manage.py runserver - devserver I get the following error when static files are requested. Quite frankly i'm completely lost with this error, has anyone an idea what this is about? HTTP GET /static/admin/css/responsive.css 500 [0.21, 127.0.0.1:59982] Exception inside application: async_to_sync can only be applied to async functions. Traceback (most recent call last): File "/home/maxehleny/.local/share/virtualenvs/mysite-EdbyOLs2/lib/python3.6/site-packages/channels/staticfiles.py", line 41, in __call__ dict(scope, static_base_url=self.base_url), receive, send File "/home/maxehleny/.local/share/virtualenvs/mysite-EdbyOLs2/lib/python3.6/site-packages/channels/staticfiles.py", line 56, in __call__ return await super().__call__(scope, receive, send) File "/home/maxehleny/.local/share/virtualenvs/mysite-EdbyOLs2/lib/python3.6/site-packages/channels/http.py", line 198, in __call__ await self.handle(scope, async_to_sync(send), body_stream) File "/home/maxehleny/.local/share/virtualenvs/mysite-EdbyOLs2/lib/python3.6/site-packages/asgiref/sync.py", line 105, in __init__ raise TypeError("async_to_sync can only be applied to async functions.") TypeError: async_to_sync can only be applied to async functions. I quite frankly have got little to no idea where the issue could lie since I don't see how this issue coming up relates to my own code. mhh -
Sum annotated field with different cases that returns multiple rows of same objects
I have referral program in my project, and I want to calculate commission that should be paid to customers. Each order can have both referral attached and/or promocode attached. Only bigger discount applies to final price. Comission is also should be calculated according to bigger discount. On my Referral queryset I calculate it like so: if referral discount >= promocode discount: ((max discount - referral discount) * orders total price) / 100 else if referral discount < promocode discount ((max discount - promocode discount) * orders total price) / 100 With real field names is what I have now: qs = self.annotate( orders_total_old_price=Sum( 'orders__bookings__old_price', filter=orders_query, output_field=models.FloatField() ), # BEFORE DISCOUNT (used for commission calculation) commission_real=Case( When( # subtract bigger discount (promocode or referral) Q(orders__promocode__isnull=False) | Q(orders__promocode__sale__lt=F('discount') / 100), then=((F('user__broker_discount__value') - F('discount')) * F('orders_total_old_price')) / 100 ), default=( Cast( F('user__broker_discount__value') - (F('orders__promocode__sale') * 100), output_field=models.IntegerField() ) * F('orders_total_old_price')) / 100, output_field=models.FloatField(), filter=orders_query ), # <------ This annotation works fine, but in returned queryset I have multiple same objects commission=Case( When(commission_real__lt=0.0, then=0.0), default=F('commission_real'), output_field=models.FloatField(), filter=orders_query ), # only positive value or 0, shown in statistic registrations=Subquery( registrations.values('registrations'), output_field=models.IntegerField(), filter=orders_query ) ) It returns correct results, but I have multiple rows for same … -
django.core.exceptions.ImproperlyConfigured: Set the REDIS_URL environment variable
I used Django-Cookiecutter to boost start my Django development. Now after building the website and wanting to host it, my choice was python anywhere and that's because I have already hosted a website there but that website wasn't built using Django-Cookiecutter. To host It on python anywhere am currently following the Django-Cookiecutter Official docs to host on pythonanywhere I have completed the first steps till it's time to run python manage.py migrate which results in the following error: django.core.exceptions.ImproperlyConfigured: Set the REDIS_URL environment variable In Full The Error Msg is : Traceback (most recent call last): File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/environ/environ.py", line 273, in get_value value = self.ENVIRON[var] File "/home/someone/.virtualenvs/smt/lib/python3.8/os.py", line 673, in __getitem__ raise KeyError(key) from None KeyError: 'REDIS_URL' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 35, in <module> execute_from_command_line(sys.argv) File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/core/management/base.py", line 82, in wrapped saved_locale = translation.get_language() File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 252, in get_language return _trans.get_language() File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__ if settings.USE_I18N: File "/home/someone/.virtualenvs/smt/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in … -
How to properly work with URL mapping in Django and what a beginner needs to know
path('book/int:pk', views.BookDetailView.as_view(), name='book-detail') should we use ^ $ \d and in which situations re_path(r'^book/(?P\d+)$', views.BookDetailView.as_view(), name='book-detail') -
Tell me, is it possible that there is an error in the url?
Someone tell me, set up categories for the blog according to one old documentation, added 3 categories, all with posts, but they are not displayed, what is the problem? models.py f rom django.db import models from django.contrib.auth.models import User STATUS = ( (0,"Draft"), (1,"Publish") ) class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts') updated_on = models.DateTimeField(auto_now= True) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE,) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def get_cat_list(self): k = self.category # for now ignore this instance method breadcrumb = ["dummy"] while k is not None: breadcrumb.append(k.slug) k = k.parent for i in range(len(breadcrumb)-1): breadcrumb[i] = '/'.join(breadcrumb[-1:i-1:-1]) return breadcrumb[-1:0:-1] # Create your models here. class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField() parent = models.ForeignKey('self',blank=True, null=True ,related_name='children', on_delete=models.CASCADE,) class Meta: #enforcing that there can not be two categories under a parent with same slug # __str__ method elaborated later in post. use __unicode__ in place of # __str__ if you are using python 2 unique_together = ('slug', 'parent',) verbose_name_plural = "categories" def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = … -
How to upload all rows in an excel file into django model with xlrd
How can I modify this code to accept to upload all lines of data in the excel sheet provided? Curerently it only picks the values in row 2, i.e after the headers. def UploadTeacherView(request): if request.method == 'POST': form = NewTeachersForm(request.POST, request.FILES) if form.is_valid(): excel_file = request.FILES['file'] fd, path = tempfile.mkstemp() try: with os.fdopen(fd, 'wb') as tmp: tmp.write(excel_file.read()) book = xlrd.open_workbook(path) sheet = book.sheet_by_index(0) obj=TeacherData( school_id = sheet.cell_value(rowx=1, colx=1), code = sheet.cell_value(rowx=1, colx=2), first_name = sheet.cell_value(rowx=1, colx=3), last_name = sheet.cell_value(rowx=1, colx=4), email = sheet.cell_value(rowx=1, colx=5), phone = sheet.cell_value(rowx=1, colx=6), ) obj.save() finally: os.remove(path) else: message='Invalid Entries' else: form = NewTeachersForm() return render(request,'new_teacher.html', {'form':form,'message':message}) -
Optimizing # of SQL queries for Django using "Prefetch_related" for nested children with variable level depth
I have a Child MPTT model that has a ForeignKey to itself: class Child(MPTTModel): title = models.CharField(max_length=255) parent = TreeForeignKey( "self", on_delete=models.CASCADE, null=True, blank=True, related_name="children" ) I have a recursive Serializer as I want to show all levels of children for any given Child: class ChildrenSerializer(serializers.HyperlinkedModelSerializer): url = HyperlinkedIdentityField( view_name="app:children-detail", lookup_field="pk" ) class Meta: model = Child fields = ("url", "title", "children") def get_fields(self): fields = super(ChildrenSerializer, self).get_fields() fields["children"] = ChildrenSerializer(many=True) return fields I am trying to reduce the number of duplicate/similar queries made when accessing a Child's DetailView. The view below works for a depth of 2 - however, the "depth" is not always known or static. class ChildrenDetailView(generics.RetrieveUpdateDestroyAPIView): queryset = Child.objects.prefetch_related( "children", "children__children", # A depth of 3 will additionally require "children__children__children", # A depth of 4 will additionally require "children__children__children__children", # etc. ) serializer_class = ChildrenSerializer lookup_field = "pk" Should I be overwriting get_object and/or retrieve? How do I leverage a Child's depth (i.e. the Child's MPTT "level" field) to optimize prefetching? -
AttributeError: 'method' object has no attribute 'backend'
Traceback (most recent call last): File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Internet\Desktop\Programming\Discord\Ξ X 0 Website\Ξ X 0 Dashboard\dashboard\home\views.py", line 12, in home_view authenticate(request, user=user) File "C:\Users\Internet\AppData\Local\Programs\Python\Python38\lib\site-packages\django\contrib\auth\__init__.py", line 80, in authenticate user.backend = backend_path AttributeError: 'method' object has no attribute 'backend' I'm getting this error from Django when I tried creating a custom authentication system. I'm pretty sure this is coming from my views.py but I have no idea how to fix it. All the code I worked on is down below. I did some print statements to see if the code breaks somewhere and I found that authenticate(request, user=user) in views.py stops the code which causes auth.py and managers.py to not trigger. managers.py from django.contrib.auth import models class DiscordUserOAuth2Manager(models.UserManager): def create_new_discord_user(self, user): print('Inside Discord User Manager') discord_tag = '%s#%s' % (user['username'], user['discriminator']) new_user = self.create( id=user['id'], avatar=user['avatar'], public_flags=user['public_flags'], flags=user['flags'], locale=user['locale'], mfa_enabled=user['mfa_enabled'], discord_tag=discord_tag ) return new_user auth.py from django.contrib.auth.backends import BaseBackend from .models import DiscordUser from django.contrib.auth.models import User class DiscordAuthenticationBackend(BaseBackend): def authenticate(self, request, user): find_user = DiscordUser.objects.filter(id=user['id']) if len(find_user) == 0: print("User was not found. Saving...") new_user = DiscordUser.objects.create_new_discord_user (user) print(new_user) return new_user return find_user … -
How to send axios request to localhost?
I am currently trying to send an API request from a mobile app to a django server running on my computer. I am receiving a network error every time I try and send the request, regardless of the different headers I use (I am new to this so my headers could be totally wrong). Here is the request I am sending: export async function requestPrediction(img) { const url = 'http://127.0.0.1:8000/v1/predict/'; const data = new FormData(); data.append('file', { uri: img, type: 'image/jpeg', name: 'imageName' }); try { console.log(url, data); let resp = await Axios.post(url, data, { headers: { 'accept': 'application/json', 'Accept-Language': 'en-US,en;q=0.8', 'Content-Type': `multipart/form-data; boundary=${data._boundary}`, } }); console.log('######################\n','ACTION_RESULTS_SUCCESS',resp.data); } catch(error) { console.log('######################\n','ACTION_RESULTS_ERROR', error); } } I am pretty certain the URL I am sending to is the right address. When I type that URL in on my computer while the server is running I do not receive an error that the page wasn't found. Thanks for the help. I can post any server-side code that might be necessary. -
Test django application: need to delete a row in postgres, and then recover
I have a Django application which is interacting with postgres. To test application I want to delete several rows from a table and see the outcome of it on the retrieved data (queries are pretty complex, so to just see whether everything is good is hard otherwise). Whats the best practice to approach such a case? Most straightforward is to write down all of the data for the deleted rows, delete rows, test app, then reinsert the rows, but I feel like its too manual, time consuming and not how it should be done. Besides there is a small chance of missing something out and/or sometimes the model can't be easily deleted without deleting other model rows when they are related by a foreign key.