Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Efficiently updating a large number of records based on a field in that record using Django
I have about a million Comment records that I want to update based on that comment's body field. I'm trying to figure out how to do this efficiently. Right now, my approach looks like this: update_list = [] qs = Comments.objects.filter(word_count=0) for comment in qs: model_obj = Comments.objects.get(id=comment.id) model_obj.word_count = len(model_obj.body.split()) update_list.append(model_obj) Comment.objects.bulk_update(update_list, ['word_count']) However, this hangs and seems to time out in my migration process. Does anybody have suggestions on how I can accomplish this? -
Django Related Through Models Not Using Soft Delete Model Manager
i am trying to retrieve only rows in a through model that are not deleted but keep getting all rows including the deleted ones. learnt it's a bug with using use_for_related_fields in the model manager according to this link: https://code.djangoproject.com/ticket/17746 i am trying to implement a follow/unfollow system like on social media platforms below is my code sample class BasicModelQuerySet(models.QuerySet): def delete(self): return self.update(is_deleted = True, deleted_at = timezone.now()) def erase(self): return super(BasicModelQuerySet, self).delete() class BasicModelManager(models.Manager): use_for_related_fields = True def get_queryset(self): return BasicModelQuerySet(self.model, self._db).filter(is_deleted = False).filter(deleted_at__isnull = True) class BasicModel(models.Model): deleted_at = models.DateTimeField(blank = True, null = True) is_deleted = models.BooleanField(default = False) objects = BasicModelManager() everything = models.Manager() class Meta: abstract = True class Listing(BasicModel): watchers = models.ManyToManyField(User, through = 'Watching', related_name = 'watchers') class Watching(BasicModel): user = models.ForeignKey(User, on_delete = models.RESTRICT, related_name = 'watching') listing = models.ForeignKey(Listing, on_delete = models.RESTRICT, related_name = 'spectators') sample tables id | user | ------------- 1 | User A | 2 | User B | id | listing | ---------------- 1 | Listing A | 2 | Listing B | # watchings table id | user | listing | deleted_at | is_deleted | ------------------------------------------------------------ 1 | User A | Listing A | | … -
error "Can only use .dt accessor with datetimelike values"
how can say me why i gived an error when i add this part in my views django new = output_df.groupby([output_df['Date and Time'].dt.date, 'PCR POS/Neg']).size().unstack(fill_value=0) new.sort_values(by=['Date and Time'], ascending=True) new['Total per date'] = output_df.groupby([output_df['Date and Time'].dt.date])['PCR POS/Neg'].count() new.loc['Total', :] = new.sum(axis=0) -
Django datetime fromisoformat: argument must be str
Hi I had this error while try to running server. It may cause by the datetime field. Can someone check it for me. models.py class Post(models.Model): author = models.ForeignKey("auth.User", on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) def publish(self): self.published_date = timezone.now self.save() def approve_comments(self): return self.comments.filter(approve_comment=True) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey('mblog.Post', related_name='comments', on_delete=models.CASCADE) author = models.CharField(max_length=100) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) approve_comment = models.BooleanField(default=False) def approve(self): self.approve_comment = True self.save() def get_absolute_url(self): return reverse("post_detail", kwargs={"pk": self.pk}) def __str__(self): return self.text views.py class PostListView(ListView): model = models.Post def get_queryset(self): return models.Post.objects.filter(published_date__lte=timezone).order_by('-published_date') class DraftListView(LoginRequiredMixin,ListView): login_url = '/login/' redirect_field_name = 'mblog/post_list.html' model = models.Post def get_queryset(self): return models.Post.objects.filter(published_date__isnull=True).order_by('created_date') And had anyway better to set default for the DateTimeField? Thanks for your time. -
django-session-security forcefully log out when closes tab
I'm currently using Django 3.2 and just try to integrate django-session-security to logout after session expiring. It's working fine. But I would like to ask, Is it possible to set forcefully log out when user closes tab? -
Django Model method that uses data from the model
I want to generate unique codes (e.g. "DXGH") and save it as a field in one of my models. The problem I have is that I do not know how to check against previously generated codes whenever a new object is created. Currently my models.py looks something like this: def code_gen(): random_string = '' for _ in range(4): random_string += chr(random.randint(97,122)) return random_string class Room(models.Model): room_code = models.CharField(default=code_gen) #other fields def __str__(self): return self.room_code #other methods def code_gen_unique(self): #I know the code below is incorrect code_list = [] for object in Room.Objects.all(): code_list.append(object.room_code) while True: temp_code = code_gen() if temp_code in code_list: continue break return temp_code Ideally I would set the default value of room_code to code_gen_unique, but I can't declare code_gen_unique() before my Room class, nor after it. I expect there is a much easier solution than I have considered, and would appreciate any help very much! Cheers -
Is there a way to access a private .zip S3 object with a django app's .ebextension config file deployed on elastic beanstalk
We have a django app deployed on elastic beanstalk, and added a feature that accesses an oracle DB. cx-Oracle requires the Oracle client library (instant client), and we would like to have the .zip for the library available as a private object in our S3 bucket, public object is not an option. We want to avoid depending on an Oracle link with wget. I am struggling to develop a .config file in the .ebextensions directory that will install the .zip S3 any time it is deployed. How can was set-up the config to install on deployment? os: Amazon Linux AMI 1 -
Import & Export Django Package Foreign Key CSV File Import Issue
I'm trying to import scores for student data and I keep getting the error message that the query doesn't match on the import. I tried designating the import to look at the state_province field as the foreign key, but I don't think I have it written correctly. Secondly for some reason on my date field keeps failing the null constraint which I'm not understanding why since the excel file data is in the correct format. I set in the model null=true for now to bypass.Here is my code. I appreciate the help. Thank you STUDENT MODEL # Where Basic Student Data Is Stored class Student(models.Model): studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True) student_name = models.CharField(max_length = 50) first_name = models.CharField(max_length = 50, default = "") last_name = models.CharField(max_length = 50,default = "") gender = models.CharField(max_length = 1,default = "") birth_date = models.DateField(blank= True) student_grade = models.CharField(max_length = 2, default = "") home_room = models.CharField(max_length = 5, default = "") student_enrollment = models.CharField(max_length = 2, default = "") school_number = models.CharField(max_length = 15, default = "") email = models.EmailField(default = "") projected_graduation_year = models.CharField(max_length = 4, default = "") counseling_goal = models.TextField(max_length = 500, … -
How to correctly use Fetch in JavaScript and Django?
I am trying to make a METAR decoder as shown: I am using fetch in Vanilla js and I plan to send the entered code to a Django view. From the Django view, the decoded data will be taken and displayed in the template. views.py def ToolsPageView(request): if request.method == "POST": jsonData = json.loads(request.body) metarCode = jsonData.get('Metar') return JsonResponse("Success", safe=False) return render(request, 'app/tools.html') urls.py ... path("tools", views.ToolsPageView, name="tools") tools.html <div class="metar-code-decode"> <form method="POST" action="{% url 'tools' %}" id="metar-form"> {% csrf_token %} <input type="text" placeholder="Enter METAR: " id="metar-value"> <br> <input type="submit" id="metar-button"> </form> </div> tool.js function getDecodedMetar() { let formButton = document.querySelector("#metar-button"); formButton.onclick = function (e) { let metarCode = document.querySelector("#metar-value").value; sendMetar(metarCode); //e.preventDefault(); //getMetar(metarCode); }; } function sendMetar(metarCode) { fetch('/tools', { method: "POST", headers: { "X-CSRFToken": getCookie("csrftoken"), }, body: JSON.stringify({ Metar: metarCode, }), }); } I have used the same code for POST using fetch where I had to let user update his/her profile. And that worked. But, this does not work and the error keeps on changing from time to time after restarting the server. At the first try, there was no error produced and the server also showed a POST request being made. And the latest error which I … -
django error "Can only use .dt accessor with datetimelike values"
On my django app i gived this error AttributeError at / Can only use .dt accessor with datetimelike values line 28, in home results,output_df,new =results1(file_directory,file_directory2) line 111, in results1 new = output_df.groupby([output_df['Date and Time'].dt.date, 'PCR POS/Neg']).size().unstack(fill_value=0) Who can explain me what i have to change ? views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pandas as pd import datetime from datetime import datetime as td import os from collections import defaultdict def home(request): if request.method == 'POST': uploaded_file = request.FILES['document'] uploaded_file2 = request.FILES['document2'] if uploaded_file.name.endswith('.xls'): savefile = FileSystemStorage() name = savefile.save(uploaded_file.name, uploaded_file) name2 = savefile.save(uploaded_file2.name, uploaded_file2) d = os.getcwd() file_directory = d+'\\media\\'+name file_directory2 = d+'\\media\\'+name2 results,output_df,new =results1(file_directory,file_directory2) return render(request,"results.html",{"results":results,"output_df":output_df,"new":new}) return render(request, "index.html") def readfile(uploaded_file): data = pd.read_excel(uploaded_file, index_col=None) return data def results1(file1,file2): results_list = defaultdict(list) names_loc = file2 listing_file = pd.read_excel(file1, index_col=None) with open(names_loc, "r") as fp: for line in fp.readlines(): line = line.rstrip("\\\n") full_name = line.split(',') sample_name = full_name[0].split('_mean') try: if len(sample_name[0].split('SCO_')) > 1: sample_id = int(sample_name[0].split('SCO_')[1]) else: sample_id = int(sample_name[0].split('SCO')[1]) except: sample_id = sample_name[0] try: if listing_file['Test ID'].isin([sample_id]).any(): line_data = listing_file.loc[listing_file['Test ID'].isin([sample_id])] vector_name = line d_t = full_name[1].split('us_')[1].split('_') date_time = td(int(d_t[0]), int(d_t[1]), int(d_t[2]), int(d_t[3]), int(d_t[4]), int(d_t[5])) date_index = list(line_data['Collecting Date from the subject'].iteritems()) for x in … -
Access information from manytomany field django
my models.py file: # Create your models here. class Information(models.Model): id = models.CharField(max_length=200, primary_key=True) title = models.CharField(max_length=500) link = models.CharField(max_length=100) summary = models.CharField(max_length=1000) published = models.CharField(max_length = 100) def __str__(self): return self.title class Search(models.Model): id = models.CharField(max_length=100, primary_key=True) searched_titles = models.CharField(max_length=100) searched_topics = models.CharField(max_length=100) number_found_articles = models.IntegerField() def __str__(self): return self.id class Article_search(models.Model): id = models.CharField(max_length=100, primary_key=True) found_articles = models.ManyToManyField( Information) search_details = models.ManyToManyField( Search) my views.py def show_articles_with_this_filter_id(request): results = Article_search.objects.filter(pk=1) for i in results: print(i.found_articles) what gets printed in my terminal: database.Information.None my db is filled: how my db looks like I would like to print out the found_articles value. in this case: https:__www.sciencedaily.com_releases_2021_12_211202141501.htmAircraft_reveal_a_surprisingly How can I achieve this? -
Auto restart the server after capistrano deploy
I have nginx + nginx unit + django python application , and django project is is deployed by capistrano deploy.rb lock "~> 3.16.0" set :application, "mynavi" set :branch, 'master' set :deploy_to, "/var/www/html/mynavi" set :linked_dirs, fetch(:linked_dirs, []).push('static') set :keep_releases, 3 set :linked_files, %w{.env} set :repo_url, "ubuntu@git.viralworks.jp:/~/myGit/mynavi.git" production.rb set :stage, :production set :branch, 'master' server 'lion.viralworks.jp', user: 'ubuntu', roles: %w(app), primary: true namespace :deploy do desc 'Collec Static Files' task :collectImg do on roles(:app) do execute "source activate mynavi;/home/ubuntu/anaconda3/envs/mynavi/bin/python /var/www/html/mynavi/current/manage.py collectstatic --noinput" end end after :publishing, :collectImg end cap prodution deploy makes deployment successfully However, after deployment I need to restart unit manually. sudo systemctl restart unit Can I do this automatic after deployment? -
Django CSRF cookie not set error with React + Redux + Axios. Even though I added it to headers
I am using Django with React. I am fetching the csrf token from Django using get_token() method from from django.middleware.csrf import get_token. I am passing it while making post request from React using Axios. Here is the code return await Client.post(endpoint, { headers: { "Authorization": "Bearer " + getState().auth.accessToken, "X-CSRFToken": getState().auth.csrf, }, withCredentials: true, data, }); I am getting this error on my backend Forbidden (CSRF cookie not set.): I then tried to add cookie in the headers... headers: { "Authorization": "Bearer " + getState().auth.accessToken, "X-CSRFToken": getState().auth.csrf, "Cookie": getState().auth.csrf }, Still don't work Here is csrf setting in settings.py CSRF_TRUSTED_ORIGINS = [ "localhost:3000", ] CSRF_COOKIE_HTTPONLY = True -
Django REST and Pytest fixtures APIClient get_or_create alternative
I am trying to create a fixture for pytest for my client. The problem is I get the following error: ERROR tests.py::test_get_list_test - django.db.utils.IntegrityError: NOT NULL constraint failed: authtoken_token.user_id I guess I should be using an alternative to get_or_create when creating APIClient, but I am not sure how to implement something like that. This is my fixture: @pytest.fixture def client(db): api_client = APIClient() token = Token.objects.get_or_create(user__username='testuser') api_client.credentials(HTTP_AUTHORIZATION='Token ' + token.key) return api_client -
Update on related fields throws FieldDoesNotExist
Import and export work as expected but when i try to reimport the same file (update), i get this error:enter image description here resources.py class ArticleResource(resources.ModelResource): number = fields.Field(column_name="GMC", attribute="number", widget=CharWidget()) name = fields.Field(column_name="Artikelbezeichnung", attribute="name") intern_name = fields.Field(column_name="Artikelbezeichnung_intern", attribute="intern_name") brand = fields.Field(column_name="Marke", attribute="brand") base_label_number = fields.Field(column_name="Grundetikettennummer", attribute="base_label_number") barcode = fields.Field(column_name="Barcode_Produkt", attribute="barcode") layers = fields.Field(column_name="Lagen", attribute="layers") formatclass = fields.Field( column_name="FCL", attribute="formatclass", widget=ForeignKeyWidget(FormatClass, "number") ) volume = fields.Field(column_name="Volumen_in_L", attribute="volume", widget=IntegerWidget()) height = fields.Field(column_name="Höhe", attribute="height", widget=IntegerWidget()) width = fields.Field(column_name="Breite", attribute="width", widget=IntegerWidget()) comment = fields.Field(column_name="Bemerkung", attribute="comment") group_code = fields.Field( column_name="Grundetikett_A-Code", attribute="group", widget=ArticleGroupWidget(ArticleGroup, "code") ) group_name = fields.Field( column_name="Bezeichnung_Grundetikett", attribute="group", widget=ForeignKeyWidget(ArticleGroup, "name"), readonly=True, ) class Meta: model = Article use_bulk = True use_transactions = True skip_unchanged = True report_skipped = True import_id_fields = ["number"] exclude = ["id", "group", "packsize"] -
Problem in Django cooperation with esp 8266
Hello i need help with my django project . I want to run program on ESP 8266 from django website. To test I create simple program with blink diode on ESP and I made button on my django website and it works but I use "webbrowser()" in views.py and it is not looks perfect (I need to stay on this webiste, a webiste made in django, not open a new one). I need help to create something what will work like: I click the button on my django website, program in "views.py" send something to esp what runs program on it or change something in the ESP code, which is only going to run the code, and it won't open web browser. my views.py: def espON(request): on = On.objects.all() off = Off.objects.all() menu = menu.objects.all() webbrowser.open("http://my_ip/turnOn") d = {'on':on, 'off':off, 'menu':menu,} return render(request, 'on/index.html', d) ESP code: #include <ESP8266WiFi.h> #include <Ticker.h> #include <Math.h> const char* ssid = "my_ssid"; //nazwa ssid sieci const char* password = "my_password"; //haslo #define LED 5 WiFiServer server(80); void setup() { Serial.begin(115200); delay(10); pinMode(LED, OUTPUT); //Laczenie z siecia wifi Serial.println(); Serial.println(); Serial.print("Laczenie z: "); Serial.println(ssid); IPAddress ip(my_ip); //ip IPAddress gateway(my_ip2); IPAddress subnet(my_ip3); WiFi.config(ip, gateway, subnet); WiFi.begin(ssid, … -
Stripe: Recurring payment increment by the number of licenses increase
I have Django app. That allows the users to buy licenses subscriptions with stripe as a recurring payment when they are paying the subscription. The licenses are use automatically when connecting to the API. I want to change the use case: Well the user put his card on the customer portal in stripe. I can use for debting his card as the number of licenses are increasing. Is it possible? if it is how can be done it? -
Django makemessage not updating .po files for installed apps
I'm working with a current project that has existing .po files in "locale" directories in multiple installed app directories. Currently each locale directory is explicitly mentioned in the LOCALE_PATHS even though the docs state it will search for locale directories in each installed app. I wanted to remove the values in LOCALE_PATHS and just let normal discovery work, but it's not working. If I clear out LOCALE_PATHS and run manage.py makemessages it appears like it's doing something (time is spent processing), but no file changes occur. If I do makemessages --keep-pot then I can see all the .pot files are actually being created, but it's not actually creating the .po files for each language. Only if I explicitly pass a -l de do I then get an updated .po file for the language stated and a message stating "processing locale de". It SHOULD be able to look at the LANGUAGES setting or what files already exist and properly update them, but that appears to only happen if every locale directory is explicitly added into LOCALE_PATHS. If I have all the locale paths in LOCALE_PATHS then I can just run manage.py makemessages and all .po files are properly updated. This is … -
How can I Make a post request to this endpoint with my authorization header and body with django and python
Good day guys, am trying to use django and python request to make a post request to this endpoint with the authorization header and body gotten from this website. check my code below to understand what am saying. i need your lovely help to get this issue right and to make this code work. the mobile number and other field should take my django form and model input. Kindly, Check this code out. class RechargeData(models.Model, Main): user = models.ForeignKey(User, default=1,on_delete=models.CASCADE) phone_number = models.CharField(validators=[Main.phone_regex], max_length=10) network = models.CharField(choices=Main.OPERATORS, max_length=15) plan = models.IntegerField(choices=Main.PLANS) amount = models.DecimalField(max_digits=10, decimal_places=2) views.py import requests import json from .forms import RechargeForm def rechargedata(request): url = "http://127.0.0.1:8000/api/data/" payload = "{\"network\": network_id,\n\"mobile_number\": \"09037346247\",\n\"plan\": plan_id}" headers = {'Authorization': 'Token 5fd60vcdfddfxddsssfddff9a0a8742d','Content-Type': 'application/json'} response = requests.request("POST", url, headers=headers, data=payload) if request.method == "POST": form = RechargeForm(request.POST) if form.is_valid(): phone_number = form.cleaned_data['phone_number'] network = form.cleaned_data['network'] amount = form.cleaned_data['amount'] plan = form.cleaned_data['plan'] form.save context = RequestContext(request, { 'phone_number': responsedata.mobile_number, 'network': response.data.network_id, 'mobile_number': response.data.network_id, 'plan': response.data.plan_id, }) return render(request, 'embeds.html', {'context': context, 'form'; form}) else: form = RechargeForm() return render(request, 'index.html', {'context': context, 'form'; form}) How do I fix this? -
Facing an error with django channels when deploying to elastic beanstalk
I am facing an issue with websockets. When I run the program locally it works fine but when I deploy it to aws elastic beanstalk I face the following issue. I have a simple code as mentioned below. django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: playzone.wsgi:application aws:elasticbeanstalk:environment:process:http: Port: '80' Protocol: HTTP aws:elasticbeanstalk:environment:process:websocket: Port: '5000' Protocol: HTTP aws:elasticbeanstalk:environment:proxy:staticfiles: /static: static Procfile web: gunicorn my_app.wsgi websocket: daphne -b :: -p 5000 my_app.asgi:application asgi.py import os from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter,URLRouter from . import routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') application = get_asgi_application() application = ProtocolTypeRouter({ 'http': get_asgi_application(), 'websocket': URLRouter( routing.websocket_urlpatterns ) }) And there are 2 more simple files routing.py and consumers.py. I've even configured the load balancers on the environment's settings (80 - HTTP ; 5000 - HTTP). So once deployed, when I try routing to the webpage which has a websocket connection, I get an error saying WebSocket connection to 'ws://yyy.com/ws/' failed:. Please help me out on how I can fix it. Also am not using redis or any channel layer. Please help me out on how I can fix it. -
Proper way to create django rest endpoint without model
I have to create API endpoint that will take data from GET request body. It will find necessary data in already created database to perform calculation and then it should return calculation result as response. So I found a way to do it but I'm not sure if it should look like this. It works but you know :) urls.py schema_view = get_schema_view( openapi.Info( title="API Test", default_version='0.0.1', description="Test", ), public=True, ) urlpatterns = [ path('docs/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), path('equation/1/example', EquationView.as_view()), #... more paths to other equations... ] view.py def get_emission_val(req_emiss_fac): try: return Emission.objects.get(emission_factor=req_emiss_fac) except Emission.DoesNotExist: raise Http404("Emission value does not exist in database") equation_response = openapi.Response('response description', EquationResponseSerializer) @swagger_auto_schema( query_serializer=EquationRequestSerializer, responses={ '404':'Emission factor does not exist in database', '200': equation_response }, ) class EquationView(APIView): def get(self, request): emission_val = get_emission_val(request.data['emission_factor']) combusted_val = request.data['combusted_value'] emissions = combusted_val * emission_val.co2_emission return Response({'emissions':emissions}) serializers.py class EquationRequestSerializer(serializers.Serializer): emission_factor = serializers.CharField() combusted_value = serializers.FloatField() class EquationResponseSerializer(serializers.Serializer): emission = serializers.FloatField() What do you think about this approach? I'm not sure if I have to do it in this way. I'm using swagger and additional serializers for gerenerating api docs Example get request body: { "emission_factor":"Test", "combusted_value":1.0 } Example response: { "emissions": 1.5129 } -
Iterating over the keys of a dictionary, when keys are integer, now I am getting this error "TypeError: argument of type 'int' is not iterable"
I am working on pay raise of employees with particular ids. Suppose, I have 5 employees in my company. I have shown them in a employee_id_list. I want python to take input from me which consists of the particular ids of the employees, I want to raise the pay, along with their salary. Then, I am creating the dictionary out of these inputs. Now I want to iterate over the employee_id_list such that it matches with of the input ids. If it matches, I want to take the respective value of key which is salary and raise the pay. But I am getting an error. I have searched for everything present on stackoverflow but nothing matches my problem employee_id_list = [27, 25, 98, 78, 66] employee_dict = dict() while True: x = input("Enter an key to continue and 'r' for result: ").lower() if x== 'r': break try: employee_id = int(input("Enter key the Employee id: ")) salary = int(input(f"Enter the {employee_id}'s salary: ")) employee_dict[employee_id] = salary except ValueError: print("Please Enter the Integers!") continue print(employee_dict) for e_ids in employee_id_list: for key, value in employee_dict.items(): if e_ids in employee_dict[key] : employee_dict[value] = 0.8*value + value print(employee_dict) I am getting this error TypeError: argument … -
Add a dynamic initial value in Filter
I want to add a dynamic initial value for django-filter or django-autocomplete-light to my DetailView. I don’t know how best to build it with django-filter, django-autocomplete-light or without third app. I have a dependency dropdown (in my case, this is journal → journal year → journal volume) for each JournalDetailView. Dependency dropdown works with django-autocomplete-light and filter works with django-filter. I want to pass dynamic field for journal so I have ForeignKey which is used for depends dropdown for journal year and journal volume For example, In this case I have three fields: journal, journal year and journal volume. I want to pass value depends on DetailView for journal. For instance, for journal “Nature” it will pass field “Nature”; for journal “Ca-A Cancer Journal for Clinicians” it will pass “Ca-A Cancer Journal for Clinicians”. I have this I want to build this models.py class Journal(models.Model): slug = models.SlugField(unique=True) name = models.CharField(max_length=100, blank=True, null=True) class Article(models.Model, HitCountMixin): slug = models.SlugField(unique=True) journal = models.ForeignKey( "Journal", on_delete=models.SET_NULL, null=True, blank=True ) journalyear = models.ForeignKey( "JournalYear", on_delete=models.SET_NULL, null=True, blank=True ) journalvolume = models.ForeignKey( "JournalVolume", on_delete=models.SET_NULL, null=True, blank=True ) def __str__(self): return self.title class JournalYear(models.Model): journal = models.ForeignKey( "Journal", on_delete=models.SET_NULL, null=True, blank=True ) name = models.CharField(max_length=10, … -
"Uncaught ReferenceError: user is not defined at" in Django
I am trying to make an e-commerce website by following the guide of Dennis Ivy in YouTube. But in applying some logic in the checkout form, I've been facing an error that says "Uncaught ReferenceError: user is not defined at". ["Uncaught ReferenceError: user is not defined at" in the console] What I want to do is remove the 'user-info' if the user is not "AnonymousUser". And remove the 'form' if you don't need to ship the products (digital) and the user is not "AnonymousUser". Here's the checkout.html code: {% extends 'store/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-lg-6"> <div class="box-element" id="form-wrapper"> <form id="form"> <div id="user-info"> <div class="form-field"> <input required class="form-control" type="text" name="name" placeholder="Name.."> </div> <div class="form-field"> <input required class="form-control" type="email" name="email" placeholder="Email.."> </div> </div> <div id="shipping-info"> <hr> <p>Shipping Information:</p> <hr> <div class="form-field"> <input class="form-control" type="text" name="address" placeholder="Address.."> </div> <div class="form-field"> <input class="form-control" type="text" name="city" placeholder="City.."> </div> <div class="form-field"> <input class="form-control" type="text" name="state" placeholder="State.."> </div> <div class="form-field"> <input class="form-control" type="text" name="zipcode" placeholder="Zip code.."> </div> <div class="form-field"> <input class="form-control" type="text" name="country" placeholder="Zip code.."> </div> </div> <hr> <input id="form-button" class="btn btn-success btn-block" type="submit" value="Continue"> </form> </div> <br> <div class="box-element hidden" id="payment-info"> <small>Paypal Options</small> <button id="make-payment">Make Payment</button> </div> … -
How to use dart sass in python
Is there any python library to compile sass which uses the Dart Sass implementation? Currently I am using the libsass-python library. But Libsass is now deprecated Which is the current best choice to compile sass in python?