Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to store datetime filed with custom template?
I am trying to storing datetime field.But it isn't working. It says enter valid date and time. How can i do it ? html <input type="datetime-local" class="form-control required" name="date"> models date = models.DateTimeField() -
Django Channels: authentication from a websocket script to a server with Django Channel?
How can I authenticate a websocket connection to a Django Channel server? I'm using the code bellow to connect externally to a chat room, runned by Django Channels. It works ok but now I need to authenticate this connection. Any ideas? import asyncio import websockets from websockets import connect class WebsocketConn: def __init__(self, uri): self.uri = uri def __await__(self): return self._async_init().__await__() async def _async_init(self): self._conn = connect(self.uri) self.websocket = await self._conn.__aenter__() return self async def close(self): await self._conn.__aexit__(*sys.exc_info()) async def send(self, message): await self.websocket.send(message) async def receive(self): return await self.websocket.recv() async def main(): uri = "ws://ID_ADDRESS:8000/ws/chat/test/" webs_connection = await WebsocketConn(uri) #send and wait for receive webs_connection.send(json.dumps({'message':'Hello World!'})) message = webs_connection.receive() asyncio.get_event_loop().run_until_complete(main()) -
i can not register an user by using create_user() method in django
This my app's code. def register(request): if request.method == 'POST': first_name = request.POST['first_name'], last_name = request.POST['last_name'], email = request.POST['email'], username = request.POST['username'], password = request.POST['password'], password2 = request.POST['password2'], if password == password2: if User.objects.filter(username=username).exists(): return redirect('register') else: if User.objects.filter(email=email).exists(): return redirect('register') else: print(username,email,password,first_name,last_name) user = User.objects.create_user(username=username, password=password, email=email, first_name=first_name, last_name=last_name) print(username, email, password, first_name, last_name) user.save() return redirect('login') else: return redirect('register') else: return render(request,'blog/register.html') There print() function is executed. but user = User.objects.create_user() is not working. i do not understand why it is not working. [ I don't understand the problem.( browser show:)][1] Error: enter image description here -
Why Python doesn´t save my model to database using object .save()?
I have a function in views.py accepting petitions that get some text and a book pk and save the text to a fragments table and update the book text with the new fragment. The fragments are saved correctly, but the book doesn't. I get the response, but it doesn't save to the database when I manually check it. This is my code: profilelogged = validtoken(request.META['HTTP_MYAUTH']) if not profilelogged: return HttpResponse('Unauthorized', status=401) else: index = request.GET.get('id', 0) petitiontext = request.GET.get('texto', '') petitiontext = petitiontext.strip() todaynoformat = datetime.now() bookselected = Books.objects.filter(pk=index).first() actualwait = Waits.objects.filter(book=bookselected).order_by('ordernum').first() if not actualwait: response = 'MAL: No hay nadie en espera' else: profilewaiting = actualwait.profile if profilewaiting.pk == profilelogged.pk and actualwait.writting == 1: newfragment = Fragments(profile=profilelogged, book=bookselected, date=todaynoformat.isoformat(), texto=petitiontext) newfragment.save() newtextfull = bookselected.text+" "+petitiontext bookselected.text = newtextfull bookselected.save() actualwait.writting = 2 actualwait.save() response = bookselected.text else: response = 'MAL: No eres el siguiente en la lista o no estas activado para escribir' return HttpResponse(response) Forget about the waiting thing, its some waitlist i used to check if the user is able to submit fragments or not and thats working good. Any thoughts on why book is not saving to DB? I'm using this object.save() method in other functions … -
Is it correct to put non-data related methods into Django model?
My colleague and I are discussing whether it is correct to have model methods which are not directly related to the model data. For example, methods that generate links for the admin pages. Should these methods be in the model or it can be a separate function which accepts app_name as an argument? class Resource(models.Model): ... @classmethod def __admin_list_url(cls): return reverse(f'admin:{cls._meta.db_table}_changelist') @classmethod def get_admin_list_url(cls, caption='', query_string=''): if not caption: return '-' return mark_safe(f'<a href="{cls.__admin_list_url()}{query_string}" target="_blank">{caption}</a>') -
for billiard.pool map function, celery work hangs
I am using celery to schedule some of task in my django app. Some of the task are complex so i am using billiard to execute them. Celery is able to execute the task if i am using "CELERY_TASK_ALWAYS_EAGER = True" in setting.py but if i am not using this setting worker is getting hang on pool.map line. Can anyone suggest a workaround for this. I am using: django:2.1.12 python:3.6 celery:4.3.0 OS: Windows Thanks a lot in advance def marketcrawling(UserDetails, freq): pool = multiprocessing.Pool(8) tasks = ssekeyword.split(' ') func = partial(scrapmarket, freq=freq) results = pool.map(func, tasks) -
How to redirect users to login page with a class based view in Django?
So basically I want non logged in users to be sent to the login page when they attempt to access pages like the create post or profile page. I know how this is done with function based views, but I am curious how I could do this in CBV's. class CreatePostView(LoginRequiredMixin,CreateView): # ... view here I was wondering how I would redirect users if not logged in Would I need another function to do this, or is there something in Django that allows this to happen? Thanks :) -
How to load images in a for loop in django template?
For a name generator I want to show the alphabet to filter the initial but I have problem to load the images in the for loop. Here two tentatives in my .html: {% for letter in initials %} {% with letter|add:'_grey.ico' as myimage %} <a href="#" onclick="FilterByInitial()"><img width='32' height='32' src="{% static 'lists/icons/myimage' %}" alt='abc' /></a> {% endwith %} <a href="#" onclick="FilterByInitial()"><img width='32' height='32' src="{% static 'lists/icons/{{ letter }}_grey.ico' %}" alt='{{ letter }}' /></a> {% endfor %} Where initials is: initials = ascii_lowercase the network tab in my firefox gives myimage and {{ letter }}_grey.ico not found. And this works: src="{% static 'lists/icons/a_grey.ico' %}" -
Django - filtering on foreign key on third table
I'm trying to filter a table in Django based on the value of a particular field of a ForeignKey which is a filed of a third table ForignKey. class A(models.Model): user_type = models.CharField(blank=True, max_length=32) description = models.CharField(blank=True,max_length=512) class B(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) name = models.CharField(max_length=32, blank=True) surname = models.CharField(max_length=32, blank=True) user_type = models.ForeignKey(UserType,on_delete=models.SET_NULL, null=True) class C(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) test = models.CharField(blank=False,max_length=512) here is the query that I wish to make : I want to query on the C and find the user_type_id on the B then filter user_type value on A something like this (just for showing what I want): models.C.objects.filter(test="test").filter(B__user_type_id__A__user_type = 1) final result: I want to get all of the data that test="test" in table C and user_type = 1 in table A -
Django load is very slow
I am new in Django. one page of my web application load is very slow. I don't know where is the bottleneck. there is my code: model.py class Fact_CarCase(models.Model): CaseCode = models.IntegerField() FraudulantRate = models.FloatField(null=True) FraudType = models.ForeignKey('Dim_FraudType', on_delete=models.CASCADE, null=True) IssueUnit = models.ForeignKey('Dim_Units', to_field="UnitCode", related_name='Fact_CarCase_IssueUnit', on_delete=models.CASCADE) AgentUnit = models.ForeignKey('Dim_Units', to_field="UnitCode", related_name='Fact_CarCase_AgentUnit', on_delete=models.CASCADE) IncidentCity = models.ForeignKey('Dim_City', to_field="CityCode", related_name='Fact_CarCase_IncidentCity', on_delete=models.CASCADE) CaseUnit = models.ForeignKey('Dim_Units', to_field="UnitCode", related_name='Fact_CarCase_CaseUnit', on_delete=models.CASCADE) CaseDate = models.ForeignKey('Dim_Date', to_field="MasterDate", related_name='Fact_CarCase_CaseDate', on_delete=models.CASCADE) IssueDate = models.ForeignKey('Dim_Date', to_field="MasterDate", related_name='Fact_CarCase_IssueUnitDate', on_delete=models.CASCADE) LastEndosmentDate = models.ForeignKey('Dim_Date', to_field="MasterDate", related_name='Fact_CarCase_LastEndosmentDate', on_delete=models.CASCADE) DriverType = models.ForeignKey('Dim_DriverType', to_field="DriverTypeCode", related_name='Fact_CarCase_DriverType', on_delete=models.CASCADE, null=True) CarKind = models.ForeignKey('Dim_CarKind', to_field="CarKindCode", related_name='Fact_CarCase_CarKind', on_delete=models.CASCADE, null=True) CompleteCause = models.ForeignKey('Dim_CompleteCause', to_field="CompleteCauseCode", related_name='Fact_CarCase_CompleteCause', on_delete=models.CASCADE, null=True) CaseInspector = models.ForeignKey('Dim_CaseInspector', to_field="CaseInspectorCode", related_name='Fact_CarCase_CaseInspector', on_delete=models.CASCADE, null=True) slug = models.SlugField(max_length=100, null=True) DraftAmount = models.BigIntegerField(null=True) CaseOfUsage = models.ForeignKey('Dim_CaseOfUsage', to_field="CaseOfUsageCode", related_name='Fact_CarCase_CaseOfUsage', on_delete=models.CASCADE, null=True) IncidentReason = models.ForeignKey('Dim_IncidentReason', to_field="IncidentReasonCode", related_name='Fact_CarCase_IncidentReason', on_delete=models.CASCADE, null=True) CaseType = models.ForeignKey('Dim_CaseType', to_field="CaseTypeCode", related_name='Fact_CarCase_CaseType', on_delete=models.CASCADE) ReviewItems = models.ManyToManyField('Dim_ReviewItems', through='Middle_CaseReviewItems') FinalInsurerName = models.CharField(max_length=500, null=True) IncidentKind = models.CharField(max_length=500, null=True) IncidentDate = models.ForeignKey('Dim_Date', to_field="MasterDate", related_name='Fact_CarCase_IncidentDate', on_delete=models.CASCADE, null=True) # FeedBack = models.ManyToManyField('Fact_FeedBack', through='Middle_CaseFeedBack') def save(self, *args, **kwargs): self.slug = self.slug or slugify(self.CaseCode) super().save(*args, **kwargs) def __str__(self): # return self.CaseUnit.UnitTitle return '{} در تاریخ {}'.format(self.CaseUnit.UnitTitle, self.CaseDate.MasterDate_Slash) # ------------------------------------------------------------------------------ class Dim_Units(models.Model): UnitCode = models.IntegerField(unique=True) UnitTitle = models.CharField(max_length=500) def __str__(self): return self.UnitTitle # ------------------------------------------------------------------------------ class … -
How to update django model char field max length with postgres and heroku
I would like to update max length of django char field of base model and overwrite it in a concrete model that extends from parent, but when i execute migrate command on heroku bash cli appears this error: django.db.utils.OperationalError: cannot ALTER TABLE "cms_categoria" because it has pending trigger events Here i leave the change: Before class Entidad(models.Model): titulo = models.CharField(verbose_name=_("Título"), max_length=100) ... class Categoria(Entidad): ... ************ After class Entidad(models.Model): titulo = models.CharField(verbose_name=_("Título"), max_length=30) class Categoria(Entidad): titulo = models.CharField(max_length=20) ... How should I do the update ? Anybody could help me ? Thanks -
Displaying 2 forms for the same PK
i've been studying a lot about django forms to get a way for displaying a form for a model object to be created and a form for the images of that object. i've already tried with CBV FBV the best i got until now is setting a TemplateView and POST.requests for both forms although i still get an error about the id that the model image is set up to views.py: class VeiclesCreate2(TemplateView): veicle_form_class = VeicleForm image_form_class = ImageForm template_name = 'veiclesform.html' def post(self, request): post_data = request.POST or None veicle_form = self.veicle_form_class(post_data, prefix='veicle') image_form = self.image_form_class(post_data, prefix='image') context = self.get_context_data(veicle_form=veicle_form, image_form=image_form) if veicle_form.is_valid(): self.form_save(veicle_form) if image_form.is_valid(): self.form_save(image_form) return self.render_to_response(context) def form_save(self, form): obj = form.save() messages.success(self.request, "{} saved successfully".format(obj)) return obj def get(self, request, *args, **kwargs): return self.post(request, *args, **kwargs) models.py: class Veiculos (models.Model): YEAR_CHOICES = [] for r in range(1960, (datetime.now().year+1)): YEAR_CHOICES.append((r, r)) modelo = models.CharField(max_length=100) potencia = models.CharField(max_length=40) cor = models.CharField(max_length=30) preco = models.DecimalField(max_digits=8, decimal_places=2) ano = models.IntegerField(('ano'), choices=YEAR_CHOICES, default=datetime.now().year) created_time = models.DateTimeField(auto_now=True) updated_time = models.DateTimeField(auto_now_add=True) def __str__(self): return '%s %s' % (self.modelo, self.preco) def get_absolute_url(self): return reverse('category2') class Imagens (models.Model): veicle = models.ForeignKey(Veiculos, on_delete=models.CASCADE, verbose_name="imagens do veiculo") imagem = models.ImageField(upload_to='', blank=True) forms.py: from django import forms … -
Adding hours,minutes through datetime.timedelta not working?
Here I have some functions for managing leaves.I send the leaves by using django forms and which worked. But the problem is while viewing leave_detail in the function def view_your_leave_detail(request,pk): It is giving me this error: Exception Value: 'datetime.timedelta' object has no attribute 'hours' I think the one problem is while saving the Leave model I have specified start_day and end_date as the DateTimeField but I saved only dates but not times while saving the form. If it is the issue then how can I set times only auto but not date. Also with these functions, if the leave request has been accepted by the function def accept_leave(request,pk): then in the function def view_your_leave_detail(request,pk): I want to display some message like You have 1 day 1 hours 30 minutes and 30 sec remaining if leave is not completed but if leave is completed then your leave is completed message.For this I tried like this ,Is there any mistakes in my approach ? models.py class Leave(models.Model): staff = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,related_name='staff_leave') organization = models.ForeignKey(Organization,on_delete=models.CASCADE,related_name='staff_leave') sub = models.CharField(max_length=300) msg = models.TextField() start_day = models.DateTimeField() end_day = models.DateTimeField() is_accepted = models.BooleanField(default=False) is_rejected = models.BooleanField(default=False) sent_on = models.DateTimeField(auto_now_add=True) views.py def send_leave_request(request): form = MakeLeaveForm() if request.method … -
How to perform select_for_update in Django Rest Framework
I have a requirement where users will be selecting a few rows from the front end table. (In my case it is React and Antd is the UI library). When the user selects a row or rows from the frontend, those row information will be passed from frontend to the backend through ajax call, and those rows should be locked in the backend so that no other user can access the selected rows. If the rows are selected at the same time by some other user then a warning response should be sent to the user. For the backend, I'm using Django Rest Framework. I'm somewhat familiar with Django and Django Rest Framework on function-based view. For locking a row I know I've to use select_for_update method but I'm not sure how to implement it for multiple rows. Can anyone please give me backend(i.e. Django Rest Framework) code example how to achieve this. -
Django Comments NoReverseMatch
Im trying to make a comment system in my django app, and I got stuck. I am not really 100% sure what to return in the function here : article = get_object_or_404(Article, pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = article comment.save() return HttpResponseRedirect(reverse('article', kwargs={"pk": article.pk})) else: form = CommentForm() return render(request, 'news/add_comment_to_article.html', {'form': form}) What I want is to be redirected back to my article, with the path of /news/article_id (pk) My Urls : from . import views app_name = "news" urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:article_id>/', views.article, name='article'), path('articles/', views.ArticlesView.as_view(), name='articles'), path('search/', include('haystack.urls')), path('<int:pk>/comment/', views.add_comment_to_article, name='add_comment_to_post'), ] My models : from django.db import models from datetime import datetime from autoslug import AutoSlugField class Article(models.Model): title = models.CharField('title', max_length=200, blank=True) slug = AutoSlugField(populate_from='title', default="", always_update=True, unique=True) author = models.CharField('Author', max_length=200, default="") description = models.TextField('Description', default="") article_image = models.ImageField('Article Image') img2 = models.ImageField('Article Image 2', default="", blank=True) img3 = models.ImageField('Article Image 3', default="", blank=True) img4 = models.ImageField('Article Image 4', default="", blank=True) img5 = models.ImageField('Article Image 5', default="", blank=True) img6 = models.ImageField('Article Image 6', default="", blank=True) is_published = models.BooleanField(default=False) article_text = models.TextField('Article text', default="") pub_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.title class … -
Connecting two Models to create a dropdown
I want to know how I can connect 2 models to create a dropdown which is dependent on each other. As of writing, these are my models for the videos: class AMLVideo(models.Model): LANGUAGE = ( ('LAN', 'Language'), ('FR', 'French'), ('EN', 'English'), ('HIN', 'Hindi'), ('SPA', 'Spanish'), ('GER', 'German'), ) LEVEL = ( ('BEG', 'Beginner'), ('INT', 'Intermediary'), ('ADV', 'Advanced'), ) CATEGORY = ( ('ANI', 'Animal'), ('ENV', 'Environmental'), ('MOR', 'Moral'), ('FOLK', 'Folktales'), ('ADN', 'Adventure'), ('POE', 'Poems'), ('FUN', 'Funny'), ) slug = models.SlugField(max_length=50, default='Enter-Slug-Here') level = models.CharField(max_length=100, choices=LEVEL, default='level', blank=True) language = models.CharField(max_length=100, choices=LANGUAGE, default='language', blank=True) category = models.CharField(max_length=100, choices=CATEGORY, default='category', blank=True) video = EmbedVideoField(verbose_name='Videos', help_text='URL of Video') def __str__(self): return self.slug class Meta: verbose_name = "video" verbose_name_plural = "videos" This is the views which already shows the videos using an iframe def home(request): videos = AMLVideo.objects.all() # Get category from filter category = request.GET.get('category', '') if category: videos = videos.filter( category__exact=category ) # Get language from filter language = request.GET.get('language', '') if language: videos = videos.filter( language__exact=language ) # Get level from filter level = request.GET.get('level', '') if level: videos = videos.filter( level__exact=level ) videos = videos.order_by("-category", "-language", "-level") context = {'videos': videos} return render (request, 'home.html', context) Now for the dropdown, I'm … -
'WSGIRequest' object has no attribute 'page': PaginationMiddlware
Using pagination in Python 2.7 from last few years. After upgrading python to 3.6 and django from 1.6 to 2.1 started getting this error 'WSGIRequest' object has no attribute 'page' MIDDLEWARE = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'pagination.middleware.PaginationMiddleware', 'django_sorting.middleware.SortingMiddleware' ) -
sanic.exceptions.MethodNotSupported: Method GET not allowed for URL /model/parse
I am working on a rasa chatbot. For training the chatbot, I added all the training data to the nlu.md file. I added the stories to the stories.md file. I configured the domain.yml file and I also created a few custom actions that the bot should run when the user asks a particular question. Now I trained the chatbot using the rasa train command. This created a zipped file inside the models folder. I started the NLU server with the following command rasa run --enable-api -m models/nlu-20190919-171124.tar.gz For the front end, I am using django to create a web appication for the chatbot. This is the index.html file <form class="" action="" method="post"> {% csrf_token %} <input type="text" name="message"> <button type="submit" name="button">Send</button> </form> When the user types a message in the input area and clicks send, this view should run def index(request): if request.method == 'POST': user_message = request.POST['message'] response = requests.get("http://localhost:5005/model/parse",params={"q":user_message}) print(response) return redirect('home') else: return render(request, 'index.html') But when I click the send button, I get a 405 error. This is the complete error message from the NLU-server Traceback (most recent call last): File "/Users/sashaanksekar/anaconda3/lib/python3.7/site-packages/sanic/app.py", line 893, in handle_request handler, args, kwargs, uri = self.router.get(request) File "/Users/sashaanksekar/anaconda3/lib/python3.7/site-packages/sanic/router.py", line 407, … -
How to concatenate form key/values to string and assign it to Django variable?
New to web development Django and python. There is a review page with text box, in which customers write their review about the factory visit. When clicked submit it sent to Manager mail as text file. My employer wants it more like survey page so they asked to change the text box input to form based input, where customer provided with multiple labels and inputs as below. when clicked submit, a text file should be created with below info and send as mail. Name : Phone : email : precaution and safety gears given: [yes/no] Unit 1 ambience: [Very satisfied/Satisfied/Neutral/Unsatisfied/Very unsatisfied] Unit 2 ambience: [Very satisfied/Satisfied/Neutral/Unsatisfied/Very unsatisfied] Unit 3 ambience: [Very satisfied/Satisfied/Neutral/Unsatisfied/Very unsatisfied] General feedback : /text box for detailed review if any/ values given in [] are drop down values. our website built on Django framework. Below is the template file used on review page. {% extends 'page1.tmpl' %} <form id="reviewform" method="post" action="/sjfacweb/revfile/save"> <pre><textarea name="review" id="review">{{ review }}</textarea></pre> <input class="button" type="submit" name="submit" value="Save" /> </form> {% endblock content %} views.py @require_POST @csrf_protect def revfile_save(request): """ This page processes and saves review file. """ review = request.POST.get('review', "").replace('\r\n','\n') reviewfile_name = "/root/sjfacweb/" + remote.sjfacweb() remote.write_reviewfile(reviewfile_name,False,review) I think the django variable 'review' … -
base.html template only displays 1 block of code instead of multiple
I'm creating my base.html file and for some reason only one block is displaying in my base.html file at a time. I am trying to include a nav bar, a footer, and some content in base.html but it will only display one block at a time. I have a feeling it has something to do with my view class because I am only including one file at a time, however I'm fairly new to starting a Django project and I don't know the common procedure to set up a base.html file. base.html: {% block nav_bar %}{% endblock %} {% block content %}No Content to Show!!{% endblock %} {% block footer %}No Footer Available!!{% endblock %} views.py: from django.views.generic import TemplateView class HomeView(TemplateView): template_name = 'home.html' Hoping to have all blocks show up on the page at once! EDIT: home.html is my homepage content page. -
How to include django-countries package into django's UserCreationForm?
I've downloaded a django-countries package using "pip install django-countries" and I need to include a Country field which is like a drop down list with all countries in my django project which is using UserCreationForm. I am planning to create the country field and allow users to select a country with its country code and make the select field a dependent select field in correlation with a phone number field in my form. Only problem im facing now is that i downloaded the countries package and cannot seem to get the country field to show up on my form. Please tell me what changes should be made to current code. I've written country=CountryField(), and included country in the "fields" list. However, when I ran the server, an error occurred stating Unknown field(s) (country) specified for User. /* views.py */ import phonenumbers from phonenumbers import carrier from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from django_countries.fields import CountryField from validate_email import validate_email # from phonenumber_field.formfields import PhoneNumberField class UserRegisterForm(UserCreationForm): email = forms.EmailField() # phone_number = PhoneNumberField() phone_number = forms.CharField(max_length=100) country = CountryField() class Meta: model = User fields = ['username', 'email', 'phone_number', 'country'] def clean_email(self): email = … -
Django App Deployment - 504 Timeout - No module named 'encodings' (Ubuntu 18.04, Django 2.2.1, Python 3.7, Apache 2.4.29, mod-WSGI 4.6.7)
Problem: Followed standard setup for Django web app. I am using Ubuntu 18.04, Django 2.2.1, Python 3.7, Apache 2.4.29, mod-WSGI 4.6.7, and virtualenv to create a virtualenv. When I attempt to access my site (either IP or FQDN) I get a 504 Gateway Timeout Error I check the Apache2 logs and am getting the following error at 1-second intervals: Current thread 0x00007f52f8874bc0 (most recent call first): [Mon Sep 23 02:49:26.540404 2019] [core:notice] [pid 9896:tid 139994333662144] AH00051: child pid 10305 exit signal Aborted (6), possible coredump in /etc/apache2 Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' python manage.py runserver works fine and I can access through either IP or FQDN via browser from other devices. There are no problems with the database or other issues (although when using FQDN instead of IP # I am getting 404 error on CSS/JS, although rest loads - but this is potentially a separate issue) I have tried: * Resetting up virtualenv * Resetting up Apache2 * Different apache .conf arrangements * I watched @Graham Dumpleton's excellent video from PyCon Au 2010 "Getting Started with Apache/mod_wsgi." and tried to implement some of his insights Apache2 Conf WSGIRestrictEmbedded On … -
Getting "Unhandled Promise Rejection: Network Error.." when using axios on a real android device
I am experiencing a problem where I cannot fetch data using axios. To give a brief background, I am using django and django rest framework for my backend. I tried many solutions online but none of it solve the problem I have right now. The API is working properly on android and ios simulator with a slight change with the endpoint (10.0.2.2 for android, localhost for ios). Although whenever I test it on an actual android device, the problem is still reoccurring. What I have tried so far: Changing axios' endpoint to my IP Address (192.168....) Adding django cors header in my django project Adding content-type header to axios Although there's an odd behavior whenever I'm fetching through 10.0.2.2 endpoint. I receive the warning/error very late, usually around 1-2 mins. Any help would be greatly appreciated. Thanks! As for the error log: Possible Unhandled Promise Rejection (id: 0): Error: Network Error Error: Network Error at createError (blob:http://localhost:8081/1abef6a8-bc96-4487-bb8e-b72935ef91fc:113345:17) at XMLHttpRequest.handleError (blob:http://localhost:8081/1abef6a8-bc96-4487-bb8e-b72935ef91fc:113253:16) at XMLHttpRequest.dispatchEvent (blob:http://localhost:8081/1abef6a8-bc96-4487-bb8e-b72935ef91fc:29717:27) at XMLHttpRequest.setReadyState (blob:http://localhost:8081/1abef6a8-bc96-4487-bb8e-b72935ef91fc:29079:20) at XMLHttpRequest.__didCompleteResponse (blob:http://localhost:8081/1abef6a8-bc96-4487-bb8e-b72935ef91fc:28906:16) at blob:http://localhost:8081/1abef6a8-bc96-4487-bb8e-b72935ef91fc:29016:47 at RCTDeviceEventEmitter.emit (blob:http://localhost:8081/1abef6a8-bc96-4487-bb8e-b72935ef91fc:2909:37) at MessageQueue.__callFunction (blob:http://localhost:8081/1abef6a8-bc96-4487-bb8e-b72935ef91fc:2214:44) at blob:http://localhost:8081/1abef6a8-bc96-4487-bb8e-b72935ef91fc:1956:17 at MessageQueue.__guard (blob:http://localhost:8081/1abef6a8-bc96-4487-bb8e-b72935ef91fc:2168:13) axios implementation: import axios from 'axios'; const baseURL = 'http://10.0.2.2:8000/api/'; const instance = axios.create({ baseURL: baseURL, }); instance.defaults.headers.post['Content-Type'] … -
Django Model auto modified date issue
I have a model with these two fields among others - last_synced = models.DateTimeField(null=True, editable=False) modified = models.DateTimeField(auto_now=True) last_synced is null by default and modified date is updated everytime the model is updated. I have a get_syncable_models in my Model Manager which returns all rows, for which the modified date is greater than last_synced date def get_syncable_models(self): return self.filter( Q(modified__gt=F('last_synced')) | Q(last_synced__isnull=True), reviewed=True, ) The get_syncable_models functions is called by a batch process and updates all the models with last_synced = timezone.now() . However, while saving the modified date is greater than the last_synced date(because timezone.now() in the Django framework is called few milliseconds after timezone.now() is called in the application layer), so get_syncable_models function will effectively work only when last_synced is null. I am thinking of two options here - Write a save method and check if the last_synced has been changed and then add a second to the modified date. Add a "sync" flag in the model, which will be set to true by the batch job. Based on this flag, the code will add a second to the modified date. Would much appreciate if there is a cleaner Django solution? -
How can i add paystack to my django project?
kindly pardon my question; Django newbie. I am building a web app that support a subscription plan for it users using paystack. How can i integrate paystack to django?. I have checked their documentation and still i have no idea on how to integrate it to django.