Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add cropper js to django template
I am new to web development. I am trying to learn django. I have managed to come so far. I want my user to upload picture and also be able to crop the picture while uploading. I dont have any problem with img uploading but the results i found for croping is too advanced for me i dont know how to implement them. I have found below example made in django but still couldnt understand the way it works to be able to add to my own project. Any help is appreciated. Please explain to me like i am 5. I am very new to Jquery, css and everything except python. Thanks https://github.com/adriancarayol/django-cropperjs -
nginx serve both django static files and react static files
Im recently trying to impement nginx to link up my django based backend and react based frontend. Here is my nginx config file: upstream api { server backend:8000; } server { listen 8080; location /api/ { uwsgi_pass backend:8000; include /etc/nginx/uwsgi_params; } location /admin/ { uwsgi_pass backend:8000; include /etc/nginx/uwsgi_params; } # ignore cache frontend location ~* (service-worker\.js)$ { add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'; expires off; proxy_no_cache 1; } location / { root /var/www/frontend; try_files $uri /index.html; } location /static { alias /vol/static; } location /static/rest_framework/ { alias /vol/static; } } However, the issue is that my manage.py collect static will place the django static files into /vol/static however, my react build is in /var/www/frontend/ therefore when I try accessing the default / url, it returns a blank page. However, if i remove the location /static { alias /vol/static; } location /static/rest_framework/ { alias /vol/static; } It will serve my my django admin page without any css. How do i resolve this easily without putting both static files in the same directory? -
Heroku: R15 Error Memory quota vastly exceeded when loading large files
So I am new at deploying Heroku applications. I have built a django application that basically reads from a Machine Learning model (1.3GB). This model is stored as a variable via the pickle.load function: model = pickle.load(url_path) I need this model to be accessed frequently in the application. For example, each user has a the possibility to do a prediction over some stocks. When he uses the prediction functionality we will do basic operations on this ML model. After deploying the django application via Heroku, I receive the Heroku: R15 Error Memory quota vastly exceeded, that corresponds in time with the 'model=pickle.load(url_path)' operation. I believe it is expected since the model that will be stored as variable is 1.31GB and the dyno used has 512MB. I would need a way to use this variable frequently (maybe through a third party or anything else) without having to upgrade to Advanced/Enterprise dynos. This would be really appreciated. Kind regards, Marvin -
Struggling to get Django server to run in virtual environment
I'm new to using Django & Python and am having some difficulty trying to get my manage.py application to run in a virtual environment. I am receiving the following errors at the top of my models.py file: I initially thought that this was an issue with pylint not pointing at the right environment (when I switch my Python interpretter to the one outside of the virtual environment, the pylint errors disappear); however, whenever I try to run my server, I get the following error: (.venv) tjmcerlean@LAPTOP-RKLCBQLO:/mnt/c/Users/tjmce/Desktop/Git/CS50w/Project 2/commerce$ python manage.py runserverTraceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line File "/mnt/c/Users/tjmce/Desktop/Git/CS50w/Project 2/commerce/.venv/lib/python3.8/site-packages/django/__init__.py", line 1, in <module> from django.utils.version import get_version ModuleNotFoundError: No module named 'django.utils' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 12, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? This error appears to suggest that the virtual environment is not activated. However, I activated it using the location of the virtual environment (.venv/bin/activate) and … -
How do I solve a None error in a translation website
I am currently coding my first website, which is a translator in an invented language. You input a random phrase and it should get translated in the invented language. Here's the code for the translation: class TranslatorView(View): template_name= 'main/translated.html' def get (self, request, phrase, *args, **kwargs): translation = "" for letter in phrase: if letter.lower() in "a": if letter.isupper(): translation = translation + "U" else: translation = translation + "u" elif letter.lower() in "t": if letter.isupper(): translation = translation + "A" else: translation = translation + "a" elif letter.lower() in "c": if letter.isupper(): translation = translation + "G" else: translation = translation + "g" elif letter.lower() in "g": if letter.isupper(): translation = translation + "C" else: translation = translation + "c" return render(request, 'main/translator.html', {'translation': translation}) def post (self, request, *args, **kwargs): self.phrase = request.POST.get('letter') translation = self.phrase context = { 'translation': translation } return render(request,self.template_name, context ) Template where you input the phrase: {% extends "base.html"%} {% block content%} <form action="{% url 'translated' %}" method="post">{% csrf_token %} <div class="form-group"> <center><h2 class = "display-3">TRANSLATE YOUR DNA CHAIN</h2></center> <br> <br> <textarea class="form-control" name='text' id="exampleFormControlTextarea1" rows="6"></textarea> <br> <button type='Submit' class= "btn btn-primary btn-lg btn-block">Translate</button> </div> </form> {% endblock content %} Template where … -
Genrating django admin and foreignkey error
Here is my model.py : class MireilleUser(models.Model): created = models.DateTimeField( blank=True, editable=False,default=timezone.now) modified = models.DateTimeField( blank=True,default=timezone.now) uuid = models.CharField(blank=True, max_length=48,default='') firebase_id = models.CharField(max_length=256) def save(self, *args, **kwargs): """ On save, update timestamps """ if not self.id: self.created = timezone.now() self.modified = timezone.now() if not self.uuid: self.uuid = str(uuid.uuid4().hex) + str(random.randint(1000, 9999)) return super(MireilleUser, self).save(*args, **kwargs) class MireilleAppSubscription(models.Model): ACTIVE = 'AC' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' GRADUATE = 'GR' STATUS_VALUE = [ (ACTIVE, 'Active'), ('SO', 'Sophomore'), ('JR', 'Junior'), ('SR', 'Senior'), ('GR', 'Graduate'), ] STRIPE = 'ST' GOOGLE = 'GO' APPLE = 'AP' PLATFORM_VALUE = [ (STRIPE, 'STRIPE'), (GOOGLE, 'GOOGLE'), (APPLE, 'APPLE'), ] created = models.DateTimeField( blank=True, editable=False,default=timezone.now) modified = models.DateTimeField( blank=True,default=timezone.now) uuid = models.CharField(blank=True, max_length=48,default='') mireille_user = models.ForeignKey(MireilleUser,on_delete=models.PROTECT) date_begin = models.DateTimeField(blank=True, editable=True, default=timezone.now) stripe_client_id = models.CharField(blank=True, max_length=48,default='') platform = models.CharField(blank=True, max_length=2,choices=PLATFORM_VALUE) expected_end_time = models.DateTimeField(blank=True, editable=True, default=(timezone.now()+timezone.timedelta(days=8))) is_free = models.BooleanField(default=False) is_vip = models.BooleanField(default=False) promo_code = models.CharField(blank=True, max_length=128, default='') status = models.CharField(max_length=2, choices=STATUS_VALUE, default=ACTIVE) def save(self, *args, **kwargs): """ On save, update timestamps """ if not self.id: self.created = timezone.now() self.modified = timezone.now() if not self.uuid: self.uuid = str(uuid.uuid4().hex) + str(random.randint(1000, 9999)) return super(MireilleAppSubscription, self).save(*args, **kwargs) And here is my admin.py : class MireilleUser_Admin(admin.ModelAdmin): list_display = [field.name for field … -
Populating Django SQL Database
I would like create a database for my images that I could access using django. For the model I want to create something along these lines of class Images(models.Model): Image_loc = models.CharField(max_length = 200) Image_year = models.CharField(max_length = 200) Image_date = models.DateTimeField('date taken') Where image_loc is the image file location and image_year is the year that the image was taken. I would like to populate the database with multiple images. I am new to website design and django and was wondering if anyone knew how would I go about doing this? -
How to select time on my chart js graph on Django?
I'm trying to do a selection on what only will be displayed on my chart, but I don't know what it's called hehe. please help my views.py look like this. class ResView(LoginRequiredMixin, ListView): model = Rainfall template_name = 'home.html' context_object_name = 'res' paginate_by = 8 queryset = Rainfall.objects.all().order_by('-id') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["qs"] = Rainfall.objects.all() return context my chart look like this. <script> (function () { var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: [{% for i in qs %}'{{i.timestamp}}',{% endfor %}], datasets: [{ label: 'Rainfall Graph', data: [{% for i in qs %}'{{i.amount}}',{% endfor %}], lineTension: 0, backgroundColor: 'transparent', borderColor: '#c9c5c5', borderWidth: 2, pointRadius: 1, }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: false } }] }, legend: { display: false } } }) }()); Now I want to select what to display on my chart. something like a dropdown like this. That I have an option. <select> <option value="hour">Hour</option> <option value="day">Day</option> <option value="month">Month</option> </select> -
Fail to deploy Django application with standard environment to Google Cloud Compute Engine
I deployed my Django app last Wednesday and everything was ok. On the next day, I tried to deploy changes, and the Compute Engine ran into an error: INTERNAL: Internal error encountered. Also, I ran the deployment command today using the same app.yml config and nothing has changed. The same error has occurred. My app.yml: runtime: python37 instance_class: F1 env: standard entrypoint: gunicorn -b :$PORT MyProject.wsgi --timeout 600 beta_settings: cloud_sql_instances: "<project-name>:<region>:<database-name>" handlers: - url: /.* script: auto secure: always redirect_http_response_code: 301 Here are the logs: DEBUG: Running [gcloud.app.deploy] with arguments: [--quiet: "True", --verbosity: "debug", DEPLOYABLES:1: "[u'app.yaml']"] DEBUG: Loading runtimes experiment config from [gs://runtime-builders/experiments.yaml] INFO: Reading [<googlecloudsdk.api_lib.storage.storage_util.ObjectReference object at 0x7f463bc2cd10>] DEBUG: Traceback (most recent call last): File "/opt/hostedtoolcache/gcloud/290.0.1/x64/lib/googlecloudsdk/api_lib/app/runtime_builders.py", line 269, in _Read with contextlib.closing(storage_client.ReadObject(object_)) as f: File "/opt/hostedtoolcache/gcloud/290.0.1/x64/lib/googlecloudsdk/api_lib/storage/storage_api.py", line 303, in ReadObject object_=object_ref, err=http_exc.HttpException(err))) BadFileException: Could not read [<googlecloudsdk.api_lib.storage.storage_util.ObjectReference object at 0x7f463bc2cd10>]. Please retry: HTTPError 404: No such object: runtime-builders/experiments.yaml DEBUG: Experiment config file could not be read. This error is informational, and does not cause a deployment to fail. Reason: Unable to read the runtimes experiment config: [gs://runtime-builders/experiments.yaml], error: Could not read [<googlecloudsdk.api_lib.storage.storage_util.ObjectReference object at 0x7f463bc2cd10>]. Please retry: HTTPError 404: No such object: runtime-builders/experiments.yaml Traceback (most recent call last): File … -
Django-apscheduler fully working example with steps
I was wondering if there’s a fully working ( simple ) example with steps on how to use django-apscheduler?the documentation is really poor. I managed to use apacheduler library but what i like with the django specific one is that it has admin integration. Thanks in advance -
Django image not loading Page not Found Error
I'm new to Django and I'm facing a problem of loading a static file (image). I got 127.0.0.1/:1707 GET http://127.0.0.1:8000/static/css/static/images/background/1.jpg 404 (Not Found) I'm pretty sure that the problem is on the path but I can't understand where this /static/css/ comes from. Could you please help me? My settings.py file: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'evillio/static') ] My index.html file: <!-- First Page with Picture and Search Starts --> <section class="home-one home1-overlay **home1_bgi1**"> <div class="container"> <div class="row posr"> <div class="col-lg-12"> <div class="home_content"> <div class="home-text text-center"> <h2 class="fz55">Find Your Dream Home</h2> <p class="fz18 color-white">From as low as $10 per day with limited time offer discounts.</p> </div> My CSS file: home1_bgi1{ background-image: url('static/images/background/1.jpg'); -webkit-background-size: cover; background-size: cover; background-position: center center; height: 960px; -
How to Solve 'LeadForm' object has no attribute 'save' error in Django?
I am trying to submit data through form, but it's showing me thsi error 'LeadForm' object has no attribute 'save', Please let me know how I can Solve this issue. I am stuck in this from last 4 hours, but still did not find the solution. I have another page in my website where a product page is opens, and there are a form, When user submit the form then his/her information should be store in my database, But i am stuck in this, I submitted lots of forms but I am still unable to resolve this error. Here is my forms.py file... class LeadForm(forms.Form): class Meta: model = Leads exclude = ['lead_for','property_type','status','source','message','user'] fields = ['customer_name', 'customer_email', 'customer_phone'] here is my views.py file code... def leads(request): if request.method == 'POST': form = LeadForm(request.POST) if form.is_valid(): form.save() else: form = LeadForm() return HttpResponse('Fail') here is my urls.py file... path('query/sendquery', views.leads, name='leads'), here is my leads.html file... <form action="{% url 'panel:leads' %}" id="queryform" method="POST"> {% csrf_token %} <div class="chat-group mt-1"> <input class="chat-field" type="text" name="name" id="customer_name" placeholder="Your name" required=""> </div> <div class="chat-group mt-1"> <input class="chat-field" type="number" name="customer_phone" id="customer_phone" placeholder="Phone" required=""> </div> <div class="chat-group mt-1"> <input class="chat-field" type="text" name="email" id="customer_email" placeholder="Email" required=""> </div> <div … -
Django Validators
I have an Order model where I want to verify that every order's quantity doesn't exceed the actual product quantity of the product required, and I wanna achieve this by Django validators.. all of my validators for each app are being saved in a sperate file called valditaors.py now the problem, is how to pass the product model object that the Order model is referring to trough a foreign key field to the validator specified on the quantity field to verify that the product required has enough quantity and that instead of passing actual quantity field value alone. My Order model: class Order(models.Model): product = models.ForeignKey('Product', on_delete=models.RESTRICT, related_name='orders') # I want to pass this product to the same validator((check_quantity_available)) specified on the next field. quantity = models.PositiveIntegerField(validators=[MinValueValidator(1), check_quantity_available]) # in addition to this field value as well My Validator: def check_quantity_available(value): pass # how to get the product instance here throuh the Order model so I may check if it has enough quantity or not -
NoReverseMatch in Django Web application
I have been having a tough time debugging my code as to what mistakes i could have made in my urls.py or views.py or templates but can't figure it out, i would be glad if any could kindly help me out or provide suggestion that could help me out of this. Thanks. ERROR LOGS Traceback (most recent call last): File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\student_management_app\StaffViews.py", line 450, in question_add return redirect('staff_quiz_update', quiz.pk, question.pk) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\shortcuts.py", line 41, in redirect return redirect_class(resolve_url(to, *args, **kwargs)) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\shortcuts.py", line 131, in resolve_url return reverse(to, args=args, kwargs=kwargs) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\urls\base.py", line 87, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\Habib\Documents\django\django-new\student-management-system\venv\lib\site-packages\django\urls\resolvers.py", line 677, in _reverse_with_prefix raise NoReverseMatch(msg) Exception Type: NoReverseMatch at /staff_quiz_question_add/4/question/add/ Exception Value: Reverse for 'staff_quiz_update' with arguments '(4, 5)' not found. 1 pattern(s) tried: ['staff_quiz_update/(?P<pk>[0-9]+)/$'] VIEWS.PY def question_add(request, pk): # By filtering the quiz by the url keyword argument `pk` and # by the owner, which is the logged in user, we are protecting # this view at the object-level. Meaning only the owner of # quiz … -
User filtering in Django, how to return specific user's data?
Been trying to figure this out for a long time(as in days), but can't understand what to use to return one users "events". A bit new and unfamiliar so would love any help I could get. At the moment I return all users events into the calendar so everyone can go in and see/change other users events. Was therefor wondering if there is any way I can return only the logged inn user's events. All the code I believe is necessary can be seen below. Custom user model (in my account app) Models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) brukernavn = models.CharField(max_length=30, unique=True) telefon = models.CharField(max_length=10) date_joined = models.DateTimeField(verbose_name="dato skapt", auto_now_add=True) last_login = models.DateTimeField(verbose_name="siste innlogging", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['brukernavn', 'telefon'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return True Models.py class Event(models.Model): butikk = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="event", null=True) telefon = models.CharField(max_length=12, default=None) navn = models.CharField(max_length=100) type_service = models.CharField(max_length=200, default=None) beskrivelse = models.TextField() start_time = models.DateField() def __str__(self): return self.navn @property def get_html_url(self): url = reverse('event_edit', args=(self.id,)) return f'<a href="{url}"> {self.navn} </a>' Utils.py: class Calendar(HTMLCalendar): def … -
Django CBV how to handle different pk value on 2 models?
Having difficulty Django CBV DetailView to be able to incoporate with Create,Update& Delete View: I have two models, the 2nd model have a ForeignKey from the first one: How can I differentiate their pk value on their urls.py. I encounter error:404 when trying to detailView of the pk on the 2nd model. Thank you very much. Models: class Rtana(models.Model): rsc_name = models.CharField(max_length=128,unique=True) rsc = models.PositiveIntegerField(unique=True) cc = models.CharField(max_length=32,unique=True) def __str__(self): return '%s %s' % (self.rsc_name , self.rsc) def get_absolute_url(self): return reverse("app7_cbv:details",kwargs={'pk':self.pk}) class Rt(models.Model): rt_name = models.CharField(max_length=128,unique=True) rsc_no = models.ForeignKey(Rtana,related_name="route",on_delete=models.CASCADE,) rt_no = models.PositiveIntegerField(unique=True) def __str__(self): return self.rt_name def get_absolute_url(self): return reverse("app7_cbv:rtdetails",kwargs={'pk':self.pk}) Urls: app_name = "app7_cbv" urlpatterns = [ url(r'^list$',views.Rtana_List_View.as_view(),name="list"), url(r'^(?P<pk>\d+)/$',views.Rtana__Detail_View.as_view(),name="details"), url(r'^create/$',views.Rtana_Create_View.as_view(),name="create"), url(r'^update/(?P<pk>\d+)/$',views.Rtana_Update_View.as_view(),name="update"), url(r'^delete/(?P<pk>\d+)/$',views.Rtana_Delete_View.as_view(),name="delete"), url(r'^rtlist$',views.Rt_List_View.as_view(),name="rtlist"), url(r'^(?P<pk>\d+)/$',views.Rt_Detail_View.as_view(),name="rtdetails"), url(r'^rtcreate/$',views.Rt_Create_View.as_view(),name="rtcreate"), ] views.py: def index(request): return render(request,"index.html") class Rtana_List_View(ListView): model = models.Rtana context_object_name = "rtana_list" class Rtana__Detail_View(DetailView): model = models.Rtana context_object_name = "rtana_detail" template_name = "app7_cbv/rtana_detail.html" class Rt_List_View(ListView): model = models.Rt context_object_name = "rt_list" class Rt_Detail_View(DetailView): model = models.Rt context_object_name = "rt_detail" template_name = "app7_cbv/rt_detail.html" class Rtana_Create_View(CreateView): model = models.Rtana fields = ('rsc_name','rsc','cc') class Rtana_Update_View(UpdateView): model = models.Rtana fields = "__all__" class Rtana_Delete_View(DeleteView): model = models.Rtana success_url = reverse_lazy("app7_cbv:list") class Rt_Create_View(CreateView): model = models.Rt fields = "__all__" -
Django Translation (Translate Database Values)
I'm working on a project and they asked me to make the project multilingual. but they don't have specific languages, and I want to handle this in the simplest and smarter way so I thought if I use django-modeltranslation package it will be good for me. things to know: 1- there are a lot of fields that need to translate into a lot of models and columns. 2- I Im working on drf, the front end in another language. things to do : 1- I want to make dynamic serializers to handle the columns that contain translation. ex(name_en, name_fr, name_ar ...etc.) so the serializer should return the "name" key always, not "name_en" or "name_fr". I made some code and worked fine with me but it will be a headache for me and hard to cover all cases and fields that I need to translate. example code : models.py name = models.CharField(max_length=250, blank=True, null=True) translation.py from modeltranslation.translator import translator, TranslationOptions from .models import Category class CategoryTranslationOptions(TranslationOptions): fields = ('name', 'description') translator.register(Category, CategoryTranslationOptions) request_helper.py def check_language(language): if language: return language else: return "en" def check_accept_language_header(headers): is_lang = False if "Accept-Language" in headers.keys(): is_lang = True if is_lang: return check_language(headers["Accept_Language"]) else: return "en" … -
unique=True always raises exception when used with save(commit=False)
I have a model with two fields f1 and f2. f1 has a unique constraint. I have 2 ModelForms, MF1 and MF2, one for each field. In my view, I render & process the two ModelForms. is_valid() calls on both my_MF1 and my_MF2 are fine. When I save my_MF1.save(commit=False) my_MF2.save() I get a "UNIQUE constraint failed" exception on the second save call. The second call considers that the first one has already created a record with some f1 value. When I save my_MF2.save(commit=False) my_MF1.save() everything works fine. Is this the expected behavior or is this a bug? If it is not a bug, it would be impossible to have both f1 and f2 unique. I am using SQLite. -
djnago Api is Not Working in my Flutter App
My django API is not working flutter App !!! this link is working - 'https://jsonplaceholder.typicode.com/photos' but this link is not working - 'https://shopking24.herokuapp.com/api/products' Error: XMLHttpRequest error. C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/patch/core_patch.dart 894:28 get current packages/http/src/browser_client.dart 84:22 C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1450:54 runUnary C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 143:18 handleValue C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 696:44 handleValueCallback C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 725:32 _propagateToListeners C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 519:7 [_complete] C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11 _cancelAndValue C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1302:7 C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 324:14 _checkAndCall C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 329:39 dcall C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37312:58 at Object.createErrorWithStack (http://localhost:53511/dart_sdk.js:4353:12) at Object._rethrow (http://localhost:53511/dart_sdk.js:37968:16) at async._AsyncCallbackEntry.new.callback (http://localhost:53511/dart_sdk.js:37962:13) at Object._microtaskLoop (http://localhost:53511/dart_sdk.js:37794:13) at _startMicrotaskLoop (http://localhost:53511/dart_sdk.js:37800:13) at http://localhost:53511/dart_sdk.js:33309:9 Please solve my problem... -
How can get data from odoo 10 and using it in django
I want to connect Odoo to Django app using "xml-rpc" file but can't, i need some help. -
When using django.test.client.post I get Bad Request
I use pytest-django to do unit test on my django project. The view is def news(request): """ Interface for newslist """ page = 1 if request.method == 'POST': content = request.body try: content = json.loads(content) except ValueError as error: return err_response("Value Error of post: {}".format(error)) if 'page' in content: page = content['page'] articlelist = Article.objects.all().order_by('-time') paginator = Paginator(articlelist, 10) try: current_list = paginator.page(page) except InvalidPage as error: return err_response(error) # coping with the paginator ... newsnum = len(Article.objects.all()) return JsonResponse({ 'newsnum': newsnum, 'pagelist': list(pagelist), 'data': [{ 'title': newsitem.title, 'source': newsitem.source, 'time': newsitem.time.strftime("%Y-%m-%d %H:%M:%S"), 'content': newsitem.content, 'href': newsitem.href, 'image': newsitem.image, } for newsitem in current_list] }, status=200) When I use pytest-django to test it @pytest.mark.django_db def test_view_news(client): """ Test view news """ url = reverse("news") data = { 'page': 1 } response = client.post(url, data=data) assert response.status_code == 200 It gives Bad Request and code 400. But when I use client.get(), the response is normal (code 200).In the settings, I already set DEBUG = True ALLOWED_HOSTS = ['*'] Can anyone tells me what happened? -
How to Django reverse to pages created in Wagtail?
I have a Wagtail model for an object. class ObjectPage(Page): # fields, not really important I want to make the object editable by front-end users, so I have also created a generic update view to accomplish this. My question is how I can use Django's reverse() function to point to the edited object in my get_success_url() method: class EditObjectPage(LoginRequiredMixin, UpdateView): # model, template_name, and fields defined; not really important def get_success_url(self): return("ObjectPage", kwargs={"slug" : self.object.slug}) # doesn't work return("object_page_slug", kwargs={"slug" : self.object.slug}) # also doesn't work I know how to do this when I'm explicitly defining the URL name in my urls.py file, but in this case, the URL is created as a Wagtail page and is handled by this line of my urls.py: url(r"", include(wagtail_urls)), I've been searching the documentation for whether Wagtail pages are assigned names that can be reversed to, but I'm finding nothing in the official documentation or here on StackOverflow. -
Django How to add data to database from javascript
I am have created a page in django, on this page I have create a button that calls a JavaScript function which in turn gets data from a API. This part of my code works as expected as it writes the response data to the console. However I cannot seem to get that data to be inserted into the model I have created in django. I am not sure how python/javascript/models are meant to all link together. models.py from django.db import models class Set(models.Model): scry_id = models.CharField(max_length=255) code = models.CharField(max_length=255) name = models.CharField(max_length=255) set_type = models.CharField(max_length=255) release_date = models.DateField() card_count = models.IntegerField() block_code = models.CharField(max_length=255, null=True) block_name = models.CharField(max_length=255, null=True) parent_set_code = models.CharField(max_length=255, null=True) digital_only = models.BooleanField(default=False) foil_only = models.BooleanField(default=False) nonfoil_only = models.BooleanField(default=False) icon = models.CharField(max_length=255) status = models.BooleanField(default=False) def __str__(self): return self.name sets.html {% extends "main/index.html "%} {% block content %} <div class="background card"> <div class="card-body"> <button class="btn" id="setRefresh" style="border: 1px solid" onclick="setRefresh()"><i class="fas fa-sync"></i></button> </div> </div> {% endblock%} custom.js function setRefresh() { const Url="https://api.scryfall.com/sets"; fetch(Url) .then(res => res.json()) .then(data => obj = data.data) .then(() => obj.sort(function(a,b){return a.released_at.localeCompare(b.released_at);})) .then(() => { for (var i = 0; i < obj.length; i++) { //console.log(obj[i].name); } }) } -
django normalize() argument 2 must be str, not None when adding a user's bio of a custom user model
when i try to add a user's bio from the admin panel in my custom user model when i hit save the following error appears normalize() argument 2 must be str, not None here are the models in my models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email,bio, full_name, password=None): if not email: raise ValueError('Users must have an email address') if not full_name: raise ValueError('Users must have a name') user = self.model( email=self.normalize_email(email), bio=bio, full_name=full_name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, full_name, password): user = self.create_user( email=self.normalize_email(email), full_name=full_name, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name="Email",max_length=250, unique=True) username = models.CharField(max_length=30, unique=True, null=True) date_joined = models.DateTimeField(verbose_name='Date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='Last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) bio = models.TextField(null=True, blank=True) full_name = models.CharField(verbose_name="Full name", max_length=150, null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] objects = MyAccountManager() def __str__(self): return self.full_name # For checking permissions. def has_perm(self, perm, obj=None): return self.is_admin # For which users are able to view the app (everyone is) def has_module_perms(self, app_label): return True every other field is addable normally and works fine except this … -
Apply DRY to a dict where data is coming from different vars
I have two functions where I pass the dict event_data = {[...]} to the Google API. The only difference is that for update_calendar_event the data is coming from a dict. For create_calendar_event it is an obj. Do you have any idea how to apply DRY here while considering that it's these two different types? class GoogleCalendarAPI: def __init__(self) -> None: # cache_discovery=False to avoid ImportError self.service = build( "calendar", "v3", credentials=credentials, cache_discovery=False ) def _event_link(self, event_slug: str) -> str: return "https://example.com/events/" + event_slug def update_calendar_event( self, calendar_event_id: str, validated_data: Dict[str, Any], event_slug: str ) -> None: event_data = { "summary": validated_data.get("name"), "description": validated_data.get("description") + "\n\nEvent link: " + self._event_link(event_slug), "start": { "dateTime": validated_data.get("start_date").isoformat(), "timeZone": validated_data.get("timezone"), }, "end": { "dateTime": validated_data.get("end_date").isoformat(), "timeZone": validated_data.get("timezone"), }, } self.service.events().patch( calendarId=CALENDAR_ID, eventId=calendar_event_id, body=event_data ).execute() def create_calendar_event(self, event_instance) -> str: event_data = { "summary": event_instance.name, "description": event_instance.description + "\n\nEvent link: " + self._event_link(event_instance.slug), "start": { "dateTime": event_instance.start_date.isoformat(), "timeZone": event_instance.timezone, }, "end": { "dateTime": event_instance.end_date.isoformat(), "timeZone": event_instance.timezone, }, } event = ( self.service.events() .insert(calendarId=CALENDAR_ID, body=event_data) .execute() ) return event.get("id")