Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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") -
Override label offset in Fieldset for Crispy Forms
I have a Fieldset in my layout, which contains a checkbox on the first line. For the main form I've set: self.helper.layout_class = "create-label col-md-2" which aligns my labels and fields and creates an "even" form. The problem is, this gets applied within a fieldset and a checkbox gets shuffled to the right, description on the right, and it looks like it's just hanging in the middle of the screen: This is because the generated html is applying the offset generated for labels, and ends up looking like this: <div class="form-group row"> <div class="offset-md-2 col-md-10"> <div id="div_id_allow_invitees_to_add_others" class="custom-control custom-checkbox"> <input type="checkbox" name="allow_invitees_to_add_others" class="checkboxinput custom-control-input" id="id_allow_invitees_to_add_others"> <label for="id_allow_invitees_to_add_others" class="custom-control-label"> Allow invitees to add others </label> If I manually remove the offset-md-2 in the browser inspector, it displays exactly as I want - over on the left ... I just moved the Fieldset to it's own Div in the hope I could override this, but no joy. That bit of the layout is fairly simple: Div( Fieldset( _("Invitees"), Field("allow_invitees_to_add_others"), Formset("invitees"), ), css_class="", ), Can anybody advise me on how to get this checkbox over on the left! -
Django, how to convert Python dict to Javascript
In a Django app I have a dict created in a view and I want to use it in Javascript, but I get a syntax error views.py MY_TYPES = { 'use_random': 0, 'use_stages': 1, 'use_import': 2, 0: 'use_random', 1: 'use_stages', 2: 'use_import', } class Duo(View): url = 'duo/test_dict.html' def get(self, request, partner_pk): context = { 'my_types': json.dumps(MY_TYPES), } return render(request, self.url, context) test_dict.html {% load static %} <head> <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script> </head>` {% block content %} <h1> Test dict</h1> <script> my_types = {{ my_types|safe }}; </script> <script type="text/javascript" src="{% static 'js/test_dict.js' %}"></script> {% endblock content %} test_dict.js $(document).ready(function () { console.log(my_types) console.log(JSON.parse(my_types)) }); Line 2 gives the output {0: "use_random", 1: "use_stages", 2: "use_import", use_random: 0, use_stages: 1, use_import: 2} but throws the error in line 3 SyntaxError: Unexpected token o in JSON at position 1 What am I doing wrong? -
How do I implement five star rating in Django DetailView?
I'm currently working on a restaurant review site and I'm struggling with displaying a five star rating comment form in a class based DetailView page. How do I implement a five star rating system for my class based RestarurantDetail page? I would like to change the appearence on my Integerfield "rate" to a five star rating field. I would still like to display all other fields in the comment form as normal, perhaps with crispy forms (but it's perhaps not possible if I want to customize the rate field?) If you need aditional information, just let me know! Code Restaurant Model (parts of it) in Models.py class Restaurant(models.Model): name = models.CharField(max_length = 100) country = models.CharField(max_length = 75) city = models.CharField(max_length = 75) address = models.CharField(max_length = 100) categori = models.ManyToManyField(Kategori) description = models.CharField(max_length = 300, blank=True) approved = models.BooleanField(default=False) geom = PointField(null=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name class Meta: unique_together = ('country', 'city', 'adress') Comment Model in Models.py class Comment(models.Model): ALTERNATIVES_1 = ( ('Alt 1', 'Alt 1'), ('Alt 2', 'Alt 2'), ('Alt 3', 'Alt 3'), ) restaurant = models.ForeignKey(Restaurant, on_delete = models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length = 50, blank = … -
Django static folder with css and javascript wont load
Hey I have a problem with the static files directory in Django, Inside the html template I already used the {% load static %} above the link tag and in the link tag I used href="{% static 'style.css' %}" (keep in mind the style.css is in the static folder which is located in the projects root folder (after several times "still not working" I even created the same static folder with the same css file in the respective app folder... and still not working). In the settings.py I used all of the following lines one at a time and even all together STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "/static") STATIC_DIRS = ( '/static', ) the html renders perfectly fine and is showing in the browser without any errors but for whatever reason the styling just wont apply (internal and inline sytling works, but I want to use external css). There seems to be a problem in the settings.py file but since I gave the path to the static folder in any way possible, I really don't know what to do. I didnt try with .js files yet but it'll be the same problem I guess. I'm thankfull for any answer.