Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework Serializer PrimaryKeyRelatedField pass in uuid list
So, I am trying to make a social media application and users can tag other users in their post. class Post(models.Model): author = models.ForeignKey(User, related_name='posts', on_delete=models.CASCADE) caption = models.CharField(max_length=100, null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) date_created = models.DateTimeField(auto_now_add=True) date_edited = models.DateTimeField(auto_now=True) allow_comments = models.BooleanField(default=True) archived = models.BooleanField(default=False) media_file_url = models.FileField(upload_to='videos/', validators=[validate_file_extension]) tags = TaggableManager(blank=True, through=TaggedHashtag) mentioned_users = models.ManyToManyField(User, blank=True, through='MentionedUser') class MentionedUser(models.Model): id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) date_created = models.DateTimeField(auto_now_add=True) post = models.ForeignKey(Post, on_delete=models.CASCADE) tagged_user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = (('post', 'tagged_user')) ordering = ['date_created'] For serializing the uuids for the mentioned_users, I followed these instructions. Everything works fine, I can submit one uuid correctly like this: But when I try to submit more than one uuids, I get this error: Here is my serializer: class PostSerializer(TaggitSerializer, serializers.ModelSerializer): tags = TagListSerializerField() mentioned_users = serializers.PrimaryKeyRelatedField(many=True, allow_null=True, queryset=User.objects.all(), pk_field=serializers.UUIDField(format='hex')) id = serializers.CharField(read_only=True) class Meta: model = Post fields = [ 'caption', 'allow_comments', 'media_file_url', 'id', 'tags', 'mentioned_users', ] What am I doing wrong here? What is the correct way to submit list of uuids? Also, is the present method I am using efficient, any form of help would be appreciated. Thank You. Also, I tried adding double quotes … -
Django Formset not correctly populating form data
I am trying to set up a page where a Return can be made to an order, with as many ReturnItems as needed. The empty forms for additional ReturnItems are generated by JavaScript passing in the empty form HTML string created by the formset factory. When the forms are properly filled in, it works as expected. However, when I try to submit with multiple ReturnItems forms being empty, the validation of the forms do not work properly. What I don't understand is that even though the request.POST data is correct the 'reason' and 'opened' field are not populated for the forms which causes the forms to be empty and skipped, instead of raising a ValidationError for missing the product name/code. Any help or suggestions would be useful, thanks. Example of request.POST data <QueryDict: {'csrfmiddlewaretoken': ['token'], 'first_name': ['first'], 'last_name': ['last'], 'email': ['e@email.com'], 'telephone': ['12345'], 'order_id': ['123'], 'order_date': ['2022-10-05'], 'form-TOTAL_FORMS': ['2'], 'form-INITIAL_FORMS': ['0'], 'form-MIN_NUM_FORMS': ['1'], 'form-MAX_NUM_FORMS': ['15'], 'form-0-product_name': ['prod1'], 'form-0-product_code': ['code1'], 'form-0-quantity': ['2'], 'form-0-reason': ['1'], 'form-0-opened': ['False'], 'form-1-product_name': ['prod2'], 'form-1-product_code': ['code2'], 'form-1-quantity': ['3'], 'form-1-reason': ['1'], 'form-1-opened': ['False'], 'comment': ['comment']> Views.py def return_view(request): sitekey = settings.H_CAPTCHA_SITEKEY ReturnItemFormSet = formset_factory( ReturnItemForm, extra=0, min_num=1, max_num=15, validate_min=True, absolute_max=15, ) return_form = ReturnForm() return_item_formset = ReturnItemFormSet() empty_form … -
Django: How to use CreateView in one model and at the same time update a field in a second model. (Using a form in templates only)
I couldn't find a direct answer elsewhere. I created a Group Model and a GroupMember Model. My goal is that a user creates a Group via a form in templates, then automatically in the GroupMember model the fields should be filled. In particular the field is_admin should be 1, although its default value is set to 0. How to tell CreateGroupView to fill the GroupMember model? views.py class CreateGroupView(LoginRequiredMixin, CreateView): fields = ("name","description") model = Group class SingleGroupView(DetailView): model = Group class ListGroupView(ListView): model = Group models.py class Group(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) description = models.TextField(blank=True, default='') members = models.ManyToManyField(User,through="ProjectMember") def __str__(self): return self.name def save(self, *args, **kwargs): self.slug = slugify(self.name) super().save(*args, **kwargs) def get_absolute_url(self): return reverse("groups:single", kwargs={"slug": self.slug}) class GroupMember(models.Model): user = models.ForeignKey(User,related_name='user_groups',on_delete=models.CASCADE,) group = models.ForeignKey(Group, related_name="memberships",on_delete=models.CASCADE,) is_admin = models.BooleanField(default=False) def __str__(self): return self.user.username class Meta: unique_together = ("group", "user") my template to create a Group <form class="m-5" method="POST" action="{% url 'groups:create' %}" id="groupForm"> {% csrf_token %} <div class="form-group"> <label for="id_name">Name</label> <input type="text" name="name" maxlength="255" class="form-control" placeholder="Name" title="" required id="id_name"> </div> <div class="form-group"> <label for="id_description">Description</label> <textarea name="description" cols="40" rows="10" class="form-control" placeholder="Description" title="" id="id_description"></textarea> </div> <input type="submit" value="Create" class="btn btn-primary btn-large"> </form> the urls.py urlpatterns = … -
Possible Unhandled Promise Rejection (id: 0): [AxiosError: Network Error] - React Native and Django
I'm trying to get the data from Django backend for my React Native project but im getting this error Possible Unhandled Promise Rejection (id: 0): [AxiosError: Network Error] im new to react native and django but ive done this before in react js but i dont know why i cant get it to work here Here's My React Native Code import React, { useState, useEffect } from "react"; import axios from "axios"; import { StyleSheet, ScrollView, View, Text } from "react-native"; // Components import ProductCard from "../components/ProductCard"; export default function HomeScreen({ navigation }) { const [products, setProducts] = useState([]); useEffect(() => { async function fetchProducts() { const { data } = await axios.get("http://127.0.0.1:8000/api/products/"); setProducts(data); } fetchProducts(); }, []); return ( <View style={styles.container}> <ScrollView style={styles.scrollView}> {products.map((product) => ( <View style={styles.productsContainer}> <ProductCard product={product} navigation={navigation} /> </View> ))} </ScrollView> </View> ); } I also added these to settings.py INSTALLED_APPS = [ "corsheaders", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ] CORS_ALLOW_ALL_ORIGINS = True -
Integrate Stripe payment flow into django
I’m trying to integrate stripe custom payments flow into my Django ecom website as PayPal isn’t as good but the docs (https://stripe.com/docs/payments/quickstart?lang=python) for python are in the flask framework. Does anyone have boilerplate code for handling a simple transaction for this in Django (views, template etc.) -
ImportError: cannot import name 'KeyTextTransform' from 'django.contrib.postgres.fields.jsonb'
What is the new import for: ImportError: cannot import name 'KeyTextTransform' from 'django.contrib.postgres.fields.jsonb' I did some internet searching and didn't find an immediate result for the error. I am trying to upgrade from django 3.2 to django 4.1.2 -
Django Group by multiple times
In my Django models, I have class Tracker(models.Model): grade = models.ForeignKey(Grade, on_delete=models.CASCADE) teacher = models.ForeignKey(User, on_delete=models.CASCADE) student = models.ForeignKey(Student, on_delete=models.CASCADE) BREAK_TYPE_CHOICES = [ ('1', 'Toilet Pass'), ('2', 'Hall Pass'), ('3', 'Doctor Pass'), ] break_type = models.CharField(max_length=10, choices=BREAK_TYPE_CHOICES) start_date_time = models.DateTimeField(auto_now_add=True) end_date_time = models.DateTimeField(auto_now=True) status = models.BooleanField(default=False) I need to find all the breaks given in a day, group by teachers with a break up on the basis of break type. Currently, I can get breaks given in a day and group them by teachers. breaks_today = Tracker.objects.filter(status=True, start_date_time__gte=date_from, end_date_time__lte=date_to) breaks_today = breaks_today.values('teacher').order_by('teacher').annotate(count=Count('teacher')) How do I proceed with the next step, i.e. group by break types, then group by teacher? -
how to get over all kms using property method in django for render into templates?
Greeting developers,Actually i want to render overall km travel by particular vehicle from using @property method in django model . here is my models class Log(models.Model): vehicle = models.ForeignKey(Vehicle, on_delete=models.CASCADE) driver = models.ForeignKey(Driver, on_delete=models.CASCADE) date = models.DateField(default=timezone.now, blank=True, null=True) and related to that models i have onther models class Logsheet(models.Model): log = models.ForeignKey(Log, on_delete=models.CASCADE, related_name="logsheets") trip = models.IntegerField(blank=False, null=False) distance_from = models.FloatField(blank=True, null=True, default=0.0) distance_to = models.FloatField(blank=True, null=True, default=0.0) time_from = models.TimeField(blank=True, null=True) time_to = models.TimeField(blank=True, null=True) source = models.CharField(max_length=100, blank=True, null=True) destination = models.CharField(max_length=100, blank=True, null=True) doeking_km = models.FloatField(blank=True, null=True, default=0.0) def save(self, *args, **kwargs): self.doeking_km = int(float(self.distance_to)) - int(float(self.distance_from)) super(Logsheet, self).save(*args, **kwargs) where is doeking km is daily kms .. Problems I want to render over all km travel by particual vehicle using @property method so i can easily render it templates help me guys. -
Django Unit Testing - How to test all instances in a model?
I want to test all instances in a DB using Django. I have a python script that populates the DB and I want to test every single instance if it pass the test. I provide here a dummy tests.py: from django.test import TestCase from app_core.models import Item # Item model fields are: pk, first, second class PairTestCase(TestCase): def setUp(self): # This script populates the DB creating several Item instances from app_core.init import init_items def test_pair_elems_different(self): """First and second fields MUST be different inside the instance""" item = Item.objects.get(pk=1) self.assertNotEqual(item.first, item.second) As you can see, I just tested a single instance. Let's suppose the DB contains 1000 Item instances, what is the best way to test them all? The only solution that pops up in my mind is using a simple FOR loop inside test_pair_elems_different, iterating all object and comparing each instance. Is this approach correct in the context of unit testing best practices/principles? -
Complex query to calculate user balance
I have the following model (that is simplified): class CoinTransaction(models.Model): class TransactionTypes(Enum): purchase_of_coins = ('pu', 'Purchase of Coins') # Will have a positive amount conversion_into_money = ('co', 'Conversion Into Money') # Will have a negative amount earning = ('ea', 'Earning') # Will have a positive amount expense = ('ex', 'Expense') # Will have a negative amount @classmethod def get_value(cls, member): return cls[member].value[0] user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='coin_transactions') amount = models.IntegerField() transaction_type = models.CharField(max_length=2, choices=[x.value for x in TransactionTypes]) I want a query to get two values related to a given user: earned_coins and other_coins, without saving their value into the User model. The query should calculate these values exactly like this: earned_coins = 0 other_coins = 0 for transaction in CoinTransaction.objects.filter(user=user).order_by('creation_date'): amount = transaction.amount if transaction.transaction_type in [CoinTransaction.TransactionTypes.get_value('conversion_into_money'), CoinTransaction.TransactionTypes.get_value('earning')]: earned_coins = max(earned_coins + amount, 0) elif transaction.transaction_type in [CoinTransaction.TransactionTypes.get_value('purchase_of_coins'), CoinTransaction.TransactionTypes.get_value('expense')]: other_coins += amount if other_coins < 0: earned_coins = max(earned_coins + other_coins, 0) other_coins = 0 -
ValueError when using Django Model to import data from file into legacy database
I would like to use Django’s models to import data from newly arriving files into a legacy database. This should happen in the background whenever the user opens the main page of my app. Unfortunately, I am stuck with an “ValueError: Cannot assign "'Student_2": "Exam.student_id" must be a "Student" instance.” I know there are plenty of questions regarding how to solve this error but I still cannot figure out how to solve this in my case. I am not allowed to change anything about the legacy database and I have no influence on the format of the new files. This is how my database looks like: Here are some example data: This is how a file with new data looks like: This is how my models look like: class School(models.Model): school_id = models.CharField(primary_key=True, max_length=100) class Meta: managed = False db_table = 'school' class Student(models.Model): student_id = models.CharField(primary_key=True, max_length=100) school_id = models.ForeignKey('School', models.DO_NOTHING, db_column='school_id') class Meta: managed = False db_table = 'student' class Exam(models.Model): result_id = models.CharField(primary_key=True, max_length=100) grade = models.CharField(max_length=100, blank=True, null=True) student_id = models.ForeignKey('Student', models.DO_NOTHING, db_column='student_id') class Meta: managed = False db_table = 'exam' This is how I try to import the data: new = new_file.txt result_id = linecache.getline(new, … -
How to get value error of datetime in python for an if statement
I'm currently making an appointment app as a hobby and working on a portion of my app where when a user clicks on a day it returns all appointments they have for that day. I'm using datetime in the django filter and noticed a small bug. ValueError: day is out of range for month Pretty much my code in brief looks like this: dateArr = selected_date.split('-') startDate = datetime.datetime(int(dateArr[0]), int(dateArr[1]), int(dateArr[2]), 0, 0, 0, tzinfo=timezone.utc) endDate = datetime.datetime(int(dateArr[0]), int(dateArr[1]), int(dateArr[2]) + 1, 0, 0, 0, tzinfo=timezone.utc) I know I could write a helper function that checks to see if it's the last day of a month and then also add 1 to the month, or reset month to 1 if its dec 31. But is there a way to get the value code for datetime errors to use in an if statement? I looked through the docs but don't see anything. maybe value codes are a python thing and I should be looking somewhere else? thanks in advance! EDIT*** Think i found the answer to my own question here - https://docs.python.org/3/tutorial/errors.html - for anyone from the future. -
ReadingFile' object has no attribute 'get_text_from_image'
I have a python Django application. And I want to filter some sub text from extracted text. So this is how my views.py looks like: class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) content = '' if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) name_of_file = str(request.FILES['upload_file']) uploadfile.save() with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r') as f: print("Now its type is ", type(name_of_file)) print(uploadfile.image.path) # reading PDF file if uploadfile.image.path.endswith('.pdf'): content = ExtractingTextFromFile.filterAnanas(self) # ENDING Reading pdf file else: with open(os.path.join(settings.MEDIA_ROOT, uploadfile.image.path)) as f: content = f.read() return render(request, "main/create_profile.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/create_profile.html", { "form": submitted_form, }) and this is class: ExtractingTextFromFile.py class ExtractingTextFromFile: def extract_text_from_image(filename): text_factuur_verdi = [] pdf_file = wi(filename=filename, resolution=300) all_images = pdf_file.convert('jpeg') for image in all_images.sequence: image = wi(image=image) image = image.make_blob('jpeg') image = Image.open(io.BytesIO(image)) text = pytesseract.image_to_string(image, lang='eng') text_factuur_verdi.append(text) return text_factuur_verdi def __init__(self ): # class variables: self.apples_royal_gala = 'Appels Royal Gala 13kg 60/65 Generica PL Klasse I' self.ananas_crownless = 'Ananas Crownless 14kg 10 Sweet CR Klasse I' self.peen_waspeen = 'Peen Waspeen 14x1lkg 200-400 Generica BE Klasse I' self.tex_factuur_verdi = [] def make_pattern(substr): return r"(?<=" + substr + r").*?(?P<number>[0-9,.]*)\n" def filterAnanas(self): … -
How to declare and get an output parameter in store procedure in Django?
I am trying to work with store procedures. So far I am able to work with input parameters and is successfully able to retrieve records or insert etc. Now, I have a store procedure that requires an output parameter @Id. The goal is to insert a record in the database using the store procedure which I am able to that. The issue, however, I am facing is that I am not being able to get the @Id. I am using MsSQL database. I have tried various ways to get the @Id output, but it gives an error. This is the code: cursor.execute("DECLARE @Id int; exec proc_jobcardInsert @Id = @Id OUTPUT, @Stocknumber='"+Stocknumber+"', @Modalnumber='"+Modalnumber+"'") cursor.fetchone() I have also tried it like this: cursor.execute("exec proc_jobcardInsert @Stocknumber='"+Stocknumber+"', @Modalnumber='"+Modalnumber+"'") cursor.fetchone() And I also tried cursor.fetchone()[0] All of them are not working. I also one or two other things but all gives me an error stating: django.db.utils.ProgrammingError: No results. Previous SQL was not a query Data is being inserted into the database but I want the @Id at the end. Please guide me as how to achieve it and what am I doing wrong here. -
Razorpay signature verification fail even after passing all the data correctly - Django
I am trying to verify the signature with razorpay. I am receiving the data required for the verification correctly from the frontend and also passing the data correctly to the utility.verify_payment_signature(). The code is as below # setup razorpay client this is the client to whome user is paying money that's you client = razorpay.Client(auth=(settings.RAZORPAY_KEY_ID, settings.RAZORPAY_SECRET_ID)) # razorypay information razorpay_payment_id = request.data.get('razorpay_payment_id','') razorpay_order_id = request.data.get("razorpay_order_id",'') razorpay_signature = request.data.get('razorpay_signature','') # this is for verification of razorpay params_dict = { 'razorpay_order_id': razorpay_order_id, 'razorpay_payment_id': razorpay_payment_id, 'razorpay_signature': razorpay_signature, } check = client.utility.verify_payment_signature(params_dict) if check == None: #code else: #fail_payment The tutorial from which I learnt this says if the verification is successful the check should return None but instead the check is returning True, hence, failing the payment. I am unable to understand what is actually the problem. Please suggest me a solution -
AttributeError at /website/tbt.html 'User' object has no attribute 'get'
I am trying to generate a pdf from data taken by the user. in this case it contains a few fields as shown in models. It gives me an error after I hit the submit button my models.py tbt_date = models.DateField( verbose_name="Date of Creation", default=timezone.now ) selected_site = models.ForeignKey( sites_data, verbose_name="Choose a site", on_delete=models.CASCADE ) selected_block = models.ForeignKey( blocks_list, verbose_name="Choose a block", on_delete=models.SET_NULL, null=True ) tbt_report_img1 = models.ImageField( upload_to="formImages/TBT/", verbose_name="Upload Image 1" ) tbt_report_img2 = models.ImageField( upload_to="formImages/TBT/", verbose_name="Upload Image 2" ) rt_pdf = models.FileField(upload_to='pdfs/', verbose_name='PDF File', null=True) my views.py tbt_form_view = tbt_report_form() context = { "loggedInUser": request.user, "tbt_form":tbt_form_view, } return context #@login_required(login_url="user_login") def generate_tbt_report(request, t_form, selected_form, filename): selected_site = t_form.selected_site selected_block = t_form.selected_block selected_site_data = sites_data.objects.filter(name=selected_site)[0] tbt_date = t_form.tbt_date print(tbt_date) params = { "selected_site": selected_site_data, "tbt_date": tbt_date, "selected_block": selected_block, "t": t_form, "data": selected_form, "loggedInUser": request.user, } template_path = "website/tbt_report_pdf.html" temp_pdf = render_to_pdf(request, template_path, params, filename) return temp_pdf @login_required(login_url="user_login") def tbt_form(request): if request.method == "POST": t_form=tbt_report_form(request.user, request.POST, request.FILES) t_form.full_clean() print("in post") if t_form.is_valid(): print("Valid") t_form = t_form.save() filename='TBT' + ' ' + str(t_form.tbt_date) + ' ' + str(t_form.selected_block) + '.pdf' pdf = generate_tbt_report(request, t_form, filename) cv_get = tbt_report.objects.get(id = t_form.id) cv_get.rt_pdf.save(filename, File(BytesIO(pdf.content))) print("Saved") return pdf else: print("1") print(t_form) messages.error( request=request, message="Please … -
django: build a class based view that set a session object and call another view
is possible to build a class based view that set a session object and call another view? I did this with a form, but I need to set a session object just calling a url. Thanks -
Run Daphne in production on (or forwarded to?) port 443
I am trying to build a speech recognition-based application. It runs on Django with Django-channels and Daphne, and Nginx as the web server, on an Ubuntu EC2 instance on AWS. It should run in the browser, so I am using WebRTC to get the audio stream – or at least that’s the goal. I'll call my domain mysite.co here. Django serves the page properly on http://www.mysite.co:8000 and Daphne seems to run too, the logs show 2022-10-17 13:05:02,950 INFO Starting server at fd:fileno=0, unix:/run/daphne/daphne0.sock 2022-10-17 13:05:02,951 INFO HTTP/2 support enabled 2022-10-17 13:05:02,951 INFO Configuring endpoint fd:fileno=0 2022-10-17 13:05:02,965 INFO Listening on TCP address [Private IPv4 address of my EC2 instance]:8000 2022-10-17 13:05:02,965 INFO Configuring endpoint unix:/run/daphne/daphne0.sock I used the Daphne docs to set up Daphne with supervisor. There, they use port 8000. My first Nginx config file nginx.conf (I shouldn't use that one, should I?) looks like this: worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; types_hash_max_size 2048; # server_tokens off; server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: … -
Websocket fails to connect in deployment
I deployed an app using Django Channels to connect, send and receive data through a websocket. I get the backend working, but the problem is, the app fails when I try to connect to a websocket. I know this works in my local drive so I believe the problem has little to do with how I set up my websockets and more to do with deployment settings. Here is a link to the logs I get (I deployed this app to render.com): https://paste.pythondiscord.com/ I know my Redis Channels Layer is up and running (has also been deployed to render.com). This is the service address: redis-kufk:10000 These are my channels layer and cache settings in settings.py: CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "LOCATION": "redis://127.0.0.1:6379", }, } ... CACHES = { "default": { "BACKEND": "django_redis.cache.RedisCache", "LOCATION": "redis://127.0.0.1:6379", "TIMEOUT": 5 * 60, "OPTIONS": { "CLIENT_CLASS": "django_redis.client.DefaultClient" }, "KEY_PREFIX": "pairprogramming" } } REDIS_HOST_LAYER = '127.0.0.1' REDIS_PORT = 6379 ... REDIS_HOST = '127.0.0.1' REDIS_PORT = 6379 These is my asgi.py: import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'signup.settings') ... import django django.setup() ... application = ProtocolTypeRouter({ "http": get_asgi_application(), "websocket": AllowedHostsOriginValidator( JwtAuthMiddlewareStack( URLRouter(websocket_urlpatterns) ) ) }) -
Should I move windows project folder into WSL?
I'm trying to set up a work environment on a new machine and I am a bit confused how best to procede. I've set up a new windows machine and have WSL2 set-up; I plan on using that with VS Code for my development environment. I have a previous django project that I want to continue working on stored in a folder in a thumb drive. Do I move the [windows] project folder into the linux folder system and everything is magically ready to go? Will my previous virtual environment in the existing folder still work or do I need to start a new one? Is it better to just start a new folder via linux terminal and pull the project from github? I haven't installed pip, python, or django on the windows OR linux side just yet either. Any other things to look out for while setting this up would be really appreciated. I'm trying to avoid headaches later by getting it all set-up correctly now! -
Consolidating Multiple Django Projects
I want to Consolidating (Connect[Link together]) Two or Three Django Projects! like: Project_1 --> a Eshop Project_2 --> Deliveries in Our City. how its work?? -
Django Two Factor Auth combined with Rest Framework?
I'm trying to implement django two factor auth into my Rest API. Is there a possibility to implement this by using custom views and model creations? Because, at least that's the way I understood it, this library is mainly working based on default django templates and predefined routes. Is it possible to combine this library with a Rest API or should I use another library? -
Update Django model field by CSV file upload via change_form.html override
Django is still not my superpower, so I hope that some of you could help me to find a way to achieve my goal, which is: I need to find a way to get "Upload file" feature at Django admin change_form.html template. By uploading that file my app would be able to update body of the specific instance of Content model (with fields id, title and body). I already implemented solution for similar problem, which is how to add new objects by clicking custom "Upload csv" button in admin panel. I achieved it by following this solution: I added this in app's admin.py file: from .models import Content class CsvUploadForm(forms.Form): csv_file = forms.FileField() class CsvUploadAdmin(admin.ModelAdmin): change_list_template = "admin/change_list.html" def get_urls(self): urls = super().get_urls() additional_urls = [ path("upload-csv/", self.upload_csv), ] return additional_urls + urls def changelist_view(self, request, extra_context=None): extra = extra_context or {} extra["csv_upload_form"] = CsvUploadForm() return super(CsvUploadAdmin, self).changelist_view(request, extra_context=extra) def upload_csv(self, request): if request.method == "POST": form = CsvUploadForm(request.POST, request.FILES) if form.is_valid(): if request.FILES['csv_file'].name.endswith('csv'): try: decoded_file = request.FILES['csv_file'].read().decode( 'utf-8') except: self.message_user( request, "Can not decode the file, please check its content if valid CSV format", level=messages.ERROR ) return redirect("..") content_body = decoded_file content_title = request.FILES['csv_file'].name try: csv.reader(content_body.splitlines()) except: self.message_user( request, … -
Does default isolation level setting in Django depend on database?
I read Isolation level in Django documentation and it says as shown below: Like PostgreSQL itself, Django defaults to the READ COMMITTED isolation level. So, if I use Django with MySQL whose default isolation level is REPEATABLE READ: Is the default isolation level setting in Django also REPEATABLE READ? Or Is the default isolation level setting in Django READ COMMITTED? -
Error when importing models into test.py file, django
I'm trying to create a test.py file for some of my database methods in a current django project. I need to import my models.py file, but the import statement I'm using below (which follows the official Django example) is causing an error. Both test.py and models.py are already in appFolder, so is that the issue? from appFolder.models import Class1,Class2,Class3 Using only 'import models' didn't work when I ran it earlier. How can I resolve this? (I have also been running the file with the command './manage.py test' if that's relevant)