Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
js is not working when i am putting the bootstrap card in the form
When I am putting the whole card into the form tag in HTML then the js is not working please give me a solution. I want to put form because the enter key of the keyboard is not working. and I want that to work, and in future, i want to save the conversation into the database model , the backend is made up of Django. here is my html: <section> <div class="container py-5"> <div class="row d-flex justify-content-center"> <form> <div class="card"> <div class="card-header d-flex justify-content-between align-items-center p-3" style="border-top: 4px solid blue; background-color:#3792cd;" > <h5 class="mb-0" style="text-align:center; color:white;">Your chatbot is here! </h5> <div class="d-flex flex-row align-items-center"> <i class="fa fa-minus me-3 text-muted fa-xs"></i> <i class="fa fa-comments me-3 text-muted fa-xs"></i> <i class="fa fa-times text-muted fa-xs"></i> </div> </div> <div class="card-body" data-mdb-perfect-scrollbar="true" style="height: 440px; overflow-y:auto"> <h5>Let's Chat<img style=""></h5> <div id="chatbot"> </div> </div> <div class="card-footer text-muted d-flex justify-content-start align-items- center p-3" style="text-align:center; background-color:#3792cd"> <div class="input-group mb-0"> <input type="text" class="form-control" id="textInput" name="userMessage" placeholder="Type message" aria-label="Recipient's username" aria-describedby="button-addon2" /> <button type="submit" id="buttonInput" style="padding-top: .55rem;"> Send<i class="fa fa-send" style="padding-left: 0.5em;"></i> </button> </div> </div> </div> </form> </div> </div> <section> </form> Here is my Java scripts: function getUserResponse(){ var userText = $('#textInput').val(); var userHTML = "<div class='userhtml'><div class='img'><img style='width:36px' src='https://cdn.pixabay.com/photo/2016/11/18/23/38/child-1837375__340.png'/></div><div class='userText'><span>"+userText+"</span></div></div>"; … -
how to display alert pop up in html while error in django function
i create this project using django and python. I have a function, where if the function has an error in it, a "wrong key" message will pop up in the html. I tried to use messages, but it has a condition that it must use request. because i call this messages inside the function, so there is no request. how can I display the "wrong key" pop up, if the iv in the decrypt function cannot be used/wrong? I use try and except, so if it can't be processed, then except runs. here's my view.py code: //here's how to run html def decode(request): form = AudioFormEm() if request.method == "POST": form = AudioFormEm(request.POST, request.FILES) if form.is_valid(): form.save() last_audio = Audio_store.objects.all().last() audioem = Audio_store.objects.all().values_list('audio_em').last() key = Audio_store.objects.all().values_list('key').last() password = decrypt(bytepass, ky) print(password) context={'form':form, 'last_audio':last_audio} return render(request, "decode.html", context) context={'form':form} return render(request, "decode.html", context=context) //here's the func def decrypt(cipher_text, key): if len(key) <= key_bytes: for x in range(len(key),key_bytes): key = key + "0" assert len(key) == key_bytes private_key = hashlib.sha256(key.encode("utf-8")).digest() cipher_text = base64.b64decode(cipher_text) try: iv = cipher_text[:16] cipher = AES.new(private_key, AES.MODE_CBC, iv) return unpad(cipher.decrypt(cipher_text[16:]).decode('utf-8')) except: print("WRONG PASSWORD") messages.error(request, 'wrong key!') return redirect('decode') and here's my code in html: {% for message in … -
How to upload a link of file in postman instead of downloading file in Django
I created an API, that take xlsx as input file for post method and give me edited xlsx file. Problem is:- File I got from link and I have to download the xlsx file every time and put in postman. What I want:- directly put link in postman for input file Note:- Everytime link contains only one xlsx file I Looked for the solutions in documentations , but I can't find a thing, of How to put link for inpt file. -
Can't upload Django Image! Form won't Validate
The only thing I could find on StackOverflow was recommending adding this, enctype="multipart/form-data". but i have that in there. The error it keeps saying the image field is required. I checked my backend admin panel and the object is successfully being create, it is just the image file just doesn't upload. Am I handling it wrong? .html <form class="form-control" method="POST" action={% url 'mascot' %} enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="image" accept="image/png, image/jpeg"> <input type="text" name="name" placeholder="Mascot's Name"> <button type="submit" class="form-control btn btn-primary">Submit</button> </form> .views def mascot(request): mascots = PoopMascot.objects.all().order_by('-id') anonymous_pooper = User.objects.get(username="Anonymous_Pooper") if request.method == 'POST': form = PoopMascotForm(request.POST, request.FILES) user = request.user if form.is_valid(): new_entry = PoopMascot() new_entry.name = form.cleaned_data['name'] new_entry.image = form.cleaned_data['image'] if user.is_authenticated: new_entry.author = user else: new_entry.author = anonymous_pooper new_entry.save() else: print(form.errors) else: form = PoopMascotForm() context = {'mascots': mascots, 'form':form} return render(request, 'mascot.html', context) -
How to connect Expo GO App to Django Rest Framework Backend on localhost?
I am implementing a react native application using Expo and testing it on my iOS device using Expo Go. I have a django rest framework backend running on my local machine that I can access using my browser via http://localhost:8000 - using localhost in my react native app does not work during my fetch request. For instance: let response = await fetch(BACKEND_URL + "/shft/auth/token/obtain/", { method: "POST", body: JSON.stringify(data), headers: { "Content-Type": "application/json", }, }); returns Network request failed at node_modules\whatwg-fetch\dist\fetch.umd.js:null in setTimeout$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _allocateCallback$argument_0 at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in _callTimer at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:null in callTimers at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __callFunction at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard$argument_0 at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in __guard at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:null in callFunctionReturnFlushedQueue I have tried setting BACKEND_URL to localhost:8000 and my public IP via expo-constants import Constants from "expo-constants"; const { manifest } = Constants; const uri = `http://${manifest.debuggerHost.split(":").shift()}:8000`; But neither seem to work. I have enabled the corsheaders middleware in my DRF project and placed the @csrf_exempt decorator on my APIView's dispatch method and this error persists. I also added localhost:19000 to my CORS whitelist which is where expo seems to host its local server. What could be the problem here? Both the expo server and the django server are … -
how should I send html page in send_mail() method of django core?
So I am newbie in django and I am using send_mail() method of django.I want to send html page as a email by usnig that method.How should I do that? I have tried using jina template to send html page -
How to visualise nested functions in Django Admin documentation generator
I have a django project and inside my views.py file I have the following (theoretical) functions where you can see that the get_fullname() function is nested: def dataframerequest(request, pk): df_re = database_sql.objects.filter(projectid=pk).values() df_list = [k for k in df_re] df = pd.DataFrame(df_list) return df def get_first_name(): first_name = 'Jack' return first_name def get_last_name(): last_name = 'Smith' return last_name def get_fullname(): first_name = get_first_name() last_name = get_last_name() full_name = first_name + ' ' + last_name return full_name Is there a way to visualise nested functions throughout views.py through the Django Admin documentation generator? or is there any other product that can easily visualise the link and usage of functions between. I have resorted to using a spreadsheet to track but I wondering if there is a better way/product that can do this automatically? This is my desired output that helps tracing back where things are used. -
ERRORS: store.Product.created_by: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out
I am a beginner in Django. I am trying to build an app with user authentication. It was all ok but when I try to make a migration it occurs an error: " ERRORS: store.Product.created_by: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. " I have tried other similar problems from this site but mine is not solved yet. model.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django_countries.fields import CountryField from django.utils.translation import gettext_lazy as _ class CustomAccountManager(BaseUserManager): # create super user def create_superuser(self, email, user_name, password, **others_fields): others_fields.setdefault('is_staff', True) others_fields.setdefault('is_superuser', True) others_fields.setdefault('is_active', True) if others_fields.get('is_staff') is not True: raise ValueError( 'Superuser must be assigned to is_staff=True.' ) if others_fields.get('is_superuser') is not True: raise ValueError( 'Superuser must be assigned to is_superuser=True.' ) return self.create_user(email, user_name, password, **others_fields) # create user def create_user(self, email, user_name, password, **others_fields): if not email: raise ValueError(_('You must provide an email address.')) email = self.normalize_email(email) user = self.model(email = email, user_name=user_name, **others_fields) user.set_password(password) user.save() return user class UserBase(AbstractBaseUser, PermissionsMixin): email = models.EmailField(('email address'),unique=True) user_name = models.CharField(max_length=250, unique=True) first_name = models.CharField(max_length=250, blank=True) about = models.TextField(_('about'), max_length=500, blank=True) country = … -
Django - duplicate key error after trying to create a new model
I have a location model and it has a city field, which is a foreign key. The database is already filled with all the countries, states and cities so when I want to create a new location I will just select the city, which is connected to a state and the state is connected to a country. Here is the location model: class Location(models.Model): name = models.CharField(max_length=50, default=None, null=True, blank=True) street = models.CharField(max_length=100) additional = models.CharField(max_length=100, null=True, blank=True) city = models.OneToOneField(City, on_delete=models.CASCADE, related_name="cities") zip_code = models.CharField(max_length=30) phone = models.CharField(max_length=15, null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "location" verbose_name_plural = "locations" db_table = "locations" ordering = ["zip_code"] def __str__(self): return self.name def get_absolute_url(self): return self.slug I am trying to update a location or create it if it does not exists yet and here is the code I use to do that. It's part of a patch request: class UpdateUserSettings(generics.UpdateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = SettingsSerializer name = 'user-settings' def get_queryset(self): id = self.kwargs['pk'] return UserSettings.objects.all().filter(user=id) def patch(self, request, *args, **kwargs): user = User.objects.get(id=self.request.data.get('user')) settings = UserSettings.objects.get(user=user) form = self.request.data.get('form') if form == 'editEssentialsForm': email = self.request.data.get('email') … -
Django AWS: botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden
I am trying to connect my django project to AWS and it keeps erroring. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\cuens\PycharmProjects\frozen-brushlands-41873\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Users\cuens\PycharmProjects\frozen-brushlands-41873\venv\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\cuens\PycharmProjects\frozen-brushlands-41873\venv\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\cuens\PycharmProjects\frozen-brushlands-41873\venv\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\cuens\PycharmProjects\frozen-brushlands-41873\venv\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 187, in handle collected = self.collect() File "C:\Users\cuens\PycharmProjects\frozen-brushlands-41873\venv\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 113, in collect handler(path, prefixed_path, storage) File "C:\Users\cuens\PycharmProjects\frozen-brushlands-41873\venv\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 338, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "C:\Users\cuens\PycharmProjects\frozen-brushlands-41873\venv\lib\site-packages\django\contrib\staticfiles\management\commands\collectstatic.py", line 248, in delete_file if self.storage.exists(prefixed_path): File "C:\Users\cuens\PycharmProjects\frozen-brushlands-41873\venv\lib\site-packages\storages\backends\s3boto3.py", line 469, in exists self.connection.meta.client.head_object(Bucket=self.bucket_name, Key=name) File "C:\Users\cuens\PycharmProjects\frozen-brushlands-41873\venv\lib\site-packages\botocore\client.py", line 401, in _api_call return self._make_api_call(operation_name, kwargs) File "C:\Users\cuens\PycharmProjects\frozen-brushlands-41873\venv\lib\site-packages\botocore\client.py", line 731, in _make_api_call raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (403) when calling the HeadObject operation: Forbidden I have this as my AWS setting in the project AWS_S3_ACCESS_KEY_ID = os.environ.get('AWS_S3_ACCESS_KEY_ID') AWS_s3_SECRET_ACCESS_KEY = os.environ.get('AWS_S3_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_HOST = 's3.us-east-2.amazonaws.com' AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_CUSTOM_DOMAIN = '%s.%s' % (AWS_STORAGE_BUCKET_NAME, AWS_S3_HOST) AWS_DEFAULT_ACL = None AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, PUBLIC_MEDIA_LOCATION) DEFAULT_FILE_STORAGE = 'blog.storage_backends.MediaStorage' … -
can i select vedio file without database in django
my project is about a process video I want processing on video without using the database. I just want that select the video and then start processing on it without using a database... is it possiblein Djangoo.... -
Can't import django-tenants even I installed
I am going to use django-tenants but I couldn't import it even I installed. from django_tenants.models import DomainMixin from django_tenants.utils import get_public_schema_name, schema_context Import "django_tenants.models" could not be resolved. I can see this error. -
combine 2 csv files together with unique column with script using django
I'm trying to link two CSV files together in my script as both share the same Protein ID but with different data. i've included a snippet of both files: I've already gone ahead and printed new rows for the data_set csv below and would like to create a new row for the sequencing csv (the long letter string) under the Proteins table but unsure how to, or if it's even possible.. (in the ss below, protein sequencing would go to the right of organism taxa id) from data.models import * data_sequences_file = '../dataset/data_sequences.csv' #dataseq_file data_set_file = '../dataset/data_set.csv' #data_file pfam_descriptions_file = '../dataset/pfam_descriptions.csv' #pfam_file organism = [] pfam = [] domain = [] protein = [] with open(data_set_file) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: organism_scientific_name = row[3] data = organism_scientific_name.split() organism.append((row[1], row[2], data[0], data[1])) protein.append((row[0],row[8], row[6], row[7], row[5],row[1])) domain.append((row[5], row[4])) with open(pfam_descriptions_file) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: # pfam id - row 0 # pfam description - row 1 pfam.append((row[0], row[1])) in my models.py and admin.py i have added a new line under the class Proteins called protein_sequence which would be the new row Title. please let me know if any additional code … -
'SizedImageInstance' object has no attribute 'open'
I'm attempting to open a thumbnail of an image that was saved with django-versatileimagefield https://django-versatileimagefield.readthedocs.io/en/latest/ file = instance.image.thumbnail['1920x1080'].open(mode='rb') I'm getting the following error: 'SizedImageInstance' object has no attribute 'open' I have success with the following line of code, but I want to open the smaller version as opposed to the original version file = instance.image.open(mode='rb') If it helps, the url of the image is instance.image.thumbnail['1920x1080'].url Thanks! -
Is there any way to prevent AlpineJS from slowing down my page speed?
AlpineJS is decreasing my page speed from 95 to ~75-80. Is there anything I can do? I've tried deferring the scripts and placing them in <head>, but the effect is not much different than simply placing them at the end of <body>. I've also tried placing the JS inline but that doesn't speed anything up. Other ideas? Is there anything else I can here do to defer Alpine? <body> ... <script src="https://unpkg.com/siema@1.5.1/dist/siema.min.js"></script> <script src="https://unpkg.com/@alpinejs/intersect@3.x.x/dist/cdn.min.js"></script> <script src="https://unpkg.com/@alpinejs/collapse@3.x.x/dist/cdn.min.js"></script> <script src="https://unpkg.com/focus-visible@5.2.0/dist/focus-visible.min.js"></script> <script src="https://unpkg.com/alpinejs@3.10.5/dist/cdn.min.js"></script> </body> -
pk argument on Django blog
I'm working on a blog and I was following instructions but now I don't understand why I have problem with pk. This is my views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Category, Post def post_list(request): posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at') latest_posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')[:9] context = {'posts': posts, 'latest_posts': latest_posts} return render(request, 'home.html', context) def post_detail(request, post, pk): latest_posts = Post.objects.filter(created_at__lte=timezone.now()).order_by('created_at')[:9] post = get_object_or_404(Post, pk=pk) context = {'post': post, 'latest_posts': latest_posts} return render(request, 'post_detail.html', context) This is blog/urls.py urlpatterns = [ path('', views.post_list, name='home'), path('<slug:post>/', views.post_detail, name='post_detail'), ] This is models.py class Post(models.Model): created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="Updated at") is_published = models.BooleanField(default=False, verbose_name="Is published?") published_at = models.DateTimeField(null=True, blank=True, editable=False, verbose_name="Published at") title = models.CharField(max_length=200, verbose_name="Title") slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey('auth.User', verbose_name="Author", on_delete=models.CASCADE) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) body = RichTextField(blank=True, null=True) image = StdImageField(upload_to='featured_image/%Y/%m/%d/', variations={'standard':(1170,820),'banner':(1170,530),'thumbnail':(500,500)}) status = models.IntegerField(choices=STATUS, default=0) def get_absolute_url(self): return reverse('post_detail', args=[self.slug]) class Meta: verbose_name = "Post" verbose_name_plural = "Posts" ordering = ['-created_at'] def publish(self): self.is_published = True self.published_at = timezone.now() self.save() def __str__(self): return self.title Also, I'm adding a list of post, it might be connected with get_absolute_url {% extends "base.html" %} {% load static %} {% block … -
How Can I Sort These Many To Many Values Without a Through Table?
I am trying to compare the values in two manytomany fields...this almost works... author_confirm = Author.objects.filter(id=self.object.update_reader_id).values_list('author_confirm').order_by('pk') author = Author.objects.filter(id=self.object.update_reader_id).values_list('author').order_by('pk') authors_are_equal = list(author) == list(author_confirm) authors_are_not_equal = list(author) != list(author_confirm) This works in that it gets me the values...but doesn't seem to be cooperating with the order_by...I currently have both fields with identical values...but their PKs are transposed so it tells me these fields are not identical...which is technically correct...but I see the problem is that the PKs are not listed in order...Is there a way to do this without a Through Table? I am using UUIDs as the primary key....I'm not sure if this is relevant or not...but nonetheless I can't seem to get the values in an ordered way. Thanks in advance for any ideas. -
how to configure flet with django to build full stack application
Is there any way to use flet with django. I found both frameworks to be interesting but I haven't found any article using them together. https://www.djangoproject.com/ https://flet.dev/ I have search google and looked at stack overflow as well. I am expecting to find, how to configure flet with django. -
Connecting API data array to chartjs in django
I am trying to create a chart using chartjs and this chart is displaying API data(Stock Data). I have made the API successfully and make the data wanted in the form of an array inorder to put it in the chart. When I define the API data array as a variable and use the variable in the chart data it doesn't display anything: <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script> <script> const ctx = document.getElementById('myChart'); let y=new Array(); let theapi = fetch('api_src') .then(response => response.json()) .then(data => { const thewanted = Object.values(data)[1] for (const [key, value] of Object.entries(thewanted)) { y.push(key); } console.log(y) }) new Chart(ctx, { type: 'line', data: { labels: y, datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], borderWidth: 1 }] } , options: { scales: { y: { beginAtZero: true }}}}); </script> if you look at the labels in the chart you will find that I have used the variable as the value of the labels but it doesn't work and whan I console.log the variable I find that it contains the values that I want. Note: When I closed the pc and opened it again after time I found that it worked but when … -
How to effectively prefetch multiple columns in one model?
I'm not sure if my way of prefetching sets of items are correct. Its nested reverse foreign key fetch (another model objects and another's model's model objects). I believe models example will clarify what I mean. class Created(models.Model): created = models.DateField(default=timezone.now) class Meta: abstract = True class Category(Created): category = models.CharField(unique=True, max_length=200) class Question(Created): question = models.CharField(unique=True, max_length=200) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="questions" ) @property def correct_answer(self): return self.questions.filter(correct=True) class Answer(Created): name = models.CharField(max_length=200) correct = models.BooleanField(default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="answers") My query looks like following: Category.objects.prefetch_related("questions", "questions__answers") The above statement gives me 3 queries which I believe is too much. Or maybe it's okay? Appreciate any feedback :) -
Check if there is a next value in my django template for loop possible?
I'd like to check if there is a next value inside my for loop; If so set a comma if not do nothing. Is there something like an {% ifnext %}? -
Hosting a Django application using Railway: MIME type ('text/html') is not executable, and strict MIME type checking is enabled
I am trying to publicly host my portfolio website under my domain name: www.floriskruger.com. I have build my application using Django and I am using Railway to communicate with my GitHub profile in order to deploy this site. Everything seems to be working fine except for that none of my .css and .js files are linking properly to my website. This is what the links look like within my html file. <!-- CSS Styling --> <link rel="stylesheet" href="/templates/css/home.css" type="text/css"> <!-- JavaScript --> <script src="/templates/javascript/home.js" type="text/javascript" defer> The error that I am getting within the web console states "Refused to apply style from 'https://www.floriskruger.com/templates/css/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled." which makes me think that there is some sort of linking error with how the files are configured? However I did not have this problem on a local host. This is how my files are configured within my project I will also provide how I have my settings.py configured for my static files. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = False ALLOWED_HOSTS = ['www.floriskruger.com', 'onlineportfolio-production.up.railway.app/'] STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles') ] STATIC_URL = 'staticfiles/' STATIC_ROOT = "/www/floriskruger.com/staticfiles/" MEDIA_ROOT = '' MEDIA_URL … -
What if STATIC_ROOT and STATICFILES_DIRS have different path in Django?
I'm working on my project that is basically some type of blog. But I needed to compile different features in one project, which now it can be a problem or maybe not. In order to work I needed to have STATIC_ROOT and STATICFILES_DIRS but I cannot have them both on same location because I got error (ERRORS: ?: (staticfiles.E002) The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting.) So I searched for answer and I one guy here on stackoverflow said that he just changed location... he suggested to do it like this... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'assets_static') MEDIA_ROOT = '' MEDIA_URL = '/media/' BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] For that time it has worked, but now I'm changing some static files and they are not updating. Also, now I have folders static and asset_static. Can someone tell what is the best practice here? -
URL validation in Python - edge cases
I'm trying to write/use URL validation in python by simply analyzing the string (no http requests) but I get a lot of edge cases with the different solutions I tried. After looking at django's urlvalidator, I still have some edge cases that are misclassified: def is_url_valid(url: str) -> bool: # from django urlvalidator url_pattern = re.compile( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' # domain... r'localhost|' # localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(?::\d+)?' # optional port r'(?:/?|[/?]\S+)$', re.IGNORECASE) return bool(re.match(url_pattern, url)) we still get: >>> is_url_valid('contact.html') True Other approaches we tried: validators (python package), recommended by this SO Q&A >>> import validators >>> validators.url("firespecialties.com/bullseyetwo.html") # this is a valid url ValidationFailure(func=url, args={'value': 'firespecialties.com/bullseyetwo.html', 'public': False}) from this validating urls in python SO Q&A while urllib.parse.urlparse('contact.html') correctly assess it as a path, it fails with urllib.parse.urlparse('www.images.com/example.html')`: >>> from urllib.parse import urlparse >>> urlparse('www.images.com/example.html') ParseResult(scheme='', netloc='', path='www.images.com/example.html', params='', query='', fragment='') Adapting logic from this javascript SO Q&A -
Naming conventions to be used when creating APIs in django to be consumed in javascript
I am creating a REST API in Django to be used in JavaScript. In python, the fields are all named using snake_case, but in JavaScript it is recommended to use camelCase for variable names. How do I resolve this difference without having to rename them when I use them in JS, or do I just stick to one convention on both front and back end?