Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form save: Object is None, but form is valid
I expect the answer here is related to the problem I have, but it is unfortunately not the same and I have not been able to use it to solve the problem. I also tried following the method here, which also is not proving successful in solving this particular issue. Here is the issue: I am trying to use a simple form to create a new object. Some of the info comes from the user, some of the info comes from the system. When I process the POST request, using simple print statements I can see that the form is valid, and that it has the right data. But then when I go to save it tells me the object is None so it's not saving anything. Below follows: views.py forms.py models.py template.html What am I missing? Thank you! views.py def add_set_to_active_workout(request): workout = get_active_workout() if request.method == "POST": form = SetForm(request.POST) if form.is_valid(): print(f"Cleaned data is: {form.cleaned_data}") # This prints what I'd expect, namely, the user submitted data. set = form.save(commit=False) set.workout = workout print(f"Set is {set}") # This prints: Set is Set object (None) set.save() print("set saved") return HttpResponseRedirect(reverse("log:active_workout")) else: return render(request, "log/active_workout.html", { "set_form": form, 'workout': workout … -
Django Queryset partition data
I have a django queryset result with n results. The Django model they originate from has an attribute DateTime. I need to counts of these objects but based on the following rule, that a single count must be records that are no more than 1 minute apart. My Django Model class MyModel(models.Model): event = models.CharField(max_length="50") created_on = models.DateTimeField(auto_now=True) -
Django-mptt with different parent model
I'm adding a new feature to the existing application. This new feature will inform the user how to get an award by collecting emblems. The application will show how to get the award (I plan to use the Django-mptt or probably the Django-treebeard?). For example, to get Award A, the user needs to collect emblems as follows: — Award A: — Emblem AA — Emblem BB: — Emblem CC — Emblem DD Each emblem will be unique. Below is the model from an existing application. class EmblemClass(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE, related_name=“emblemclasses”) name = models.CharField(max_length=255) image = models.FileField(upload_to=‘images’, blank=True) description = models.TextField(blank=True, null=True, default=None) The following is the model I'm about to make: class AwardInfoClass(models.Model): user = models.ForeignKey(User, blank=False, null=False, on_delete=models.CASCADE, related_name=“awardinfoclasses”) name = models.CharField(max_length=255) description = models.TextField(blank=True, null=True, default=None) class AwardAlignmentClass(models.Model): awardinfoclass = models.ForeignKey(AwardInfoClass, on_delete=models.CASCADE) award_name = models.ForeignKey(Emblem, on_delete=models.CASCADE) award_parent = models.ForeignKey(Emblem, related_name='emblemclasses', blank=True, null=True, on_delete=models.CASCADE) In the documentation from the Django-mptt, the 'award_parent' is set to 'self' and not from a different model. I'm using an adjacency list for designing the tree and extending the existing application. Am I making the wrong model design? I have tried manually without the Django-mptt library. However, I have a … -
How to unit test for natural key in models.py in django
I want to unit test for the models.py in django. I do not know how to unit test for the function natural_key() class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=10, default="default", null=True, blank=True) @property def natural_key(self): return (self.email, self.username) I tried self.user1 = User.objects.create( email="user@email.com" username="username1") def test_natural_key_is_created(self): self.assertEquals(self.user1.natural_key, "user@email.com", "username1") but my unit test is failed -
Django F expression changes
We used to run Django 1.6 with Python 2.7 and one of our models had a field called balance, defined as: balance = models.F('gross') + models.F('refunded') - models.F('paid') the output of this field would be, for example: DecimalField('1200'). After upgrading to Django 3.2 and Python 3.9.2, balance returns: <CombinedExpression: F(gross) + F(refunded) - F(paid)> We tried to work around this by replacing balance with: @property def balance(self): return self.gross + self.refunded - self.paid and this worked until we ran into the error: FieldError: Cannot resolve keyword 'balance' into field. Does anyone know of the new correct way to keep the same functionality as we had before when using F expression to define balance? Also, I have seen some help regarding .refresh_from_db(), but when running a shell and executing: o = Order.objects.all().first() o.balance Output: <CombinedExpression: F(gross) + F(refunded) - F(paid)> o.refresh_from_db() Output: <CombinedExpression: F(gross) + F(refunded) - F(paid)> The output remains the same... Time and patience greatly appreciated fellow coders. Kindest regards -
Consume django data in nextjs
I struggle to consume rest API data with NextJs. In particular, I don't understand how to fetch the end points. My need is to loop through the data, but using posts.map, raises error data.map is not a function which is logical as my API describes an object and not a list. But then if I call only {data.id} the result is a blank page. I.e. without the mapping. What am I missing here? If possible, I'd like to convert the object into a list so I can loop and call it by the props, but how? Any input would be highly appreciated. API: { "meta": { "total_count": 3 }, "items": [ { "id": 3, "meta": { "type": "home.HomePage", "detail_url": "http://localhost:8000/api/v2/pages/3/", "html_url": "http://localhost:8000/", }, "title": "Home" }, { "id": 4, "meta": { "type": "news.NewsPage", "detail_url": "http://localhost:8000/api/v2/pages/4/", "html_url": "http://localhost:8000/breaking-news/", }, "title": "Breaking news" }, { "id": 5, "meta": { "type": "blog.BlogPage", "detail_url": "http://localhost:8000/api/v2/pages/5/", "html_url": "http://localhost:8000/blog-api/", }, "title": "blog api" } ] } Index.js import Link from "next/link" //getStaticProps export const getStaticProps = async () => { const API_URL = "http://127.0.0.1:8000/api/v2/pages/" const request = await fetch(API_URL) const data = await request.json() return{ props:{ data }, } } //route export default function Game({ data … -
Plotly graph not showing in tabs when filtering using dropdown
I'm using django-plotly-dash package to plot the graphs inside a django app. I'm trying to put the graphs in tabs where they have a dropdown to filter the result. I've been struggling for a few hours but still can't find what I've done wrong here. This is the tab layout: app_tabs = html.Div([ dcc.Tabs(id='tab-parent', children= [ dcc.Tab(label="Chart", id='tab-chart'), dcc.Tab(label="Map", id='tab-map', children=[dcc.Graph(figure={})]), ], ) ]) Here are the main layout and the callbacks: app.layout = html.Div([ html.H1('Daily Cases', style={'textAlign': 'center', 'color': colors['background']}), app_tabs, dcc.Dropdown(id='country-dropdown', options=country_options, multi=True, value=['Bangladesh', 'India', 'China', 'United States'], style={'width': "50%"}), ]) @app.callback( [Output(component_id='tab-parent', component_property='children')], [Input(component_id='country-dropdown', component_property='value')] ) def switch_tab(tab_chosen, country_list): if tab_chosen == "tab-chart": dff = daily_case[daily_case['location'].isin(country_list)] fig_chart = px.line( data_frame=dff, x='date', y='new_cases_smoothed', color='location', title='Daily Cases', labels={'new_cases_smoothed': '', 'date': ''}, template='plotly_white' ) return dcc.Graph(figure=fig_chart) elif tab_chosen == "tab-map": pass return html.P("This shouldn't be displayed for now...") Can anyone guide me what I'm doing wrong here? -
thousand seprator for integer fields input in django form
I want to have thousand separator while inputting numerical data in forms(int field),I tried using text type and JS to solve the problem but I want something more logical. I'd be glad to receive your answers with samples. best regards, -
Django. Automatic field change via admin panel
I am new to Django. I am writing the first project, I came across the following problem. We have a 'Post' model with a 'district' field. And there is a "Record" model. How to dynamically change the entry number when creating a journal entry (via the admin panel). For example, there are already 3 records with area #1, and when creating the next record, number 4 is automatically filled in. Or maybe there is a way to automatically fill in the number, immediately after creating the record? I have already achieved the automatic creation of the record number through the function. But now it does not take into account different district, but numbers all records in order, regardless of the selected district. class Post(models.Model): """Post in journal.""" def auto_number_post(): all_posts = Post.objects.all() if all_posts: next_number = max(all_posts, key=lambda x: x.number_post) return next_number.number_post + 1 return 1 number_post = models.PositiveIntegerField( default=auto_number_post, unique=True, ) district = models.ForeignKey( 'District', blank=False, null=True, on_delete=models.SET_NULL, related_name='posts', ) class District(models.Model): title = models.CharField(max_length=100) -
Django & Paypal button integration
I am integrating a paypal payment method into my website which is working perfectly.... until I try to add a description so I can view all of the order details on the paypal invoice. As soon as I add description: {} to the createOrder function below, paypal fails to load: <script> var total = '{{order.get_cart_total}}' // Render the PayPal button into #paypal-button-container paypal.Buttons({ style: { color: 'blue', shape: 'rect', }, // Set up the transaction createOrder: function(data, actions) { return actions.order.create({ purchase_units: [{ amount: { value:parseFloat(total).toFixed(2) }, description: { order_id }, }] }); }, // Finalize the transaction onApprove: function(data, actions) { return actions.order.capture().then(function(details) { console.log(JSON.stringify(details)); submitFormData() }); } }).render('#paypal-button-container'); </script> in console i get the following errors: I have added the settings below to my settings.py file: SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SESSION_COOKIE_SAMESITE = 'None' CSRF_COOKIE_SAMESITE = 'None' -
React hook is not updating state after completing a fetch request
I am trying to retrieve article data from my backend api using a fetch request and display it on screen. The request retrieves the data successfully, however when I try to update the state of the component variables using the setArticle hook, nothing happens and the request completes without passing any data in. function Home(props) { const [articles, setArticles] = useState([]); useEffect(() => { fetch(`http://localhost:8000/api/articles/`, { method: 'GET', }) .then(response => response.json()) .then(result => { if (result.error) { console.log('Error:', result.error); return false; } console.log(result); setArticles(result); console.log(articles); }) }, []) const articleList = articles.map((article) => <ArticleCard article={article} width='400'/> ) return( // return page HTML and articleList ) } export default Home; console.log(result) shows a populated array, but it doesn't get set anywhere, please help. -
How to add resizble text area in django_better_admin_arrayfield for Django admin?
I need to add resizable text area instead of textinput for Django admin using django_better_admin_arrayfield library. Model class Activity(models.Model): id = models.AutoField(primary_key=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) mood = models.ForeignKey(Mood, on_delete=models.CASCADE) title = models.CharField(max_length=255) description = models.TextField() image = models.ImageField(upload_to='./activities/images') age = models.CharField(max_length=255) duration = models.CharField(max_length=255) file = models.FileField(upload_to='./activities/files') activity = ArrayField(models.TextField()) tips = ArrayField(models.TextField()) class Meta: verbose_name_plural = 'Activities' Django admin class ActivitiesAdmin(ModelAdmin, DynamicArrayMixin): formfield_overrides = { DynamicArrayField: {'widget': DynamicArrayTextareaWidget} } list_display = ["pk", "title"] -
Sharing a DB between Django ORM & Prisma ORM
I have a Django application thats using Postgresql. At the same time the DB is being used by a Nodejs application (On the Nodejs application the queries to DB are being done using raw sql. For enhanced security I want to use Prisma to handle DB queries on the Nodejs application, I have installed Prisma using npm, next steps are: 3. Run prisma db pull to turn your database schema into a Prisma schema. 4. Run prisma generate to generate the Prisma Client. You can then start querying your database. will number "3" break my current DB?? The DB has models created using Django. I would like my DB to remain readable using Django ORM. I dont wish to write new models or change anything using the Nodejs application (Its only for fetching data from DB) -
Importing a django model into a custom script to save a new model instance
I have a script which parses emails and I wish to save parsed data in the model database. The script is in the django app where the model resides. I've imported the model and wrote the code to create the new model instance. When I run the python module in VSC I get terminal error: **``` django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. ** Other posts on StackOverflow get this far but never solve the problem. I tried importing OS and adding os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') django.setup() To the head of my module. This gets me a new error: ModuleNotFoundError: "No module named 'emails'". This confuses me greatly because I can ctrl+click on the import and it takes me to the appropriate module so it seems to see it, but not recognize the model class Emails(model.Model) within it. I also tried moving the script into the same directory as the models.py file, but had same results. -
How do I resolve Module 'my_project' has no attribute 'celery' error with Docker Compose, Django, Celery?
I can't figure out why celery isn't being recognized. Here is the full error I get when I run docker compose up (excluding everything else that works fine): celeryworker | Usage: celery [OPTIONS] COMMAND [ARGS]... celeryworker | Try 'celery --help' for help. celeryworker | celeryworker | Error: Invalid value for '-A' / '--app': celeryworker | Unable to load celery application. celeryworker | Module 'my_project' has no attribute 'celery' celeryworker exited with code 2 I'm using: Docker version 20.10.23, build 7155243 Django 4.1.7 Python 3.11 Celery 5.2.7 Dockerfile: FROM python:3.11.0 # Set environment variables ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 # Set work directory WORKDIR /code # Install dependencies RUN pip install --upgrade pip COPY requirements.txt /code/ RUN pip install -r requirements.txt # Copy the Django project COPY . /code/ docker-compose.yml services: db: image: postgres:15.2 restart: always volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres cache: image: redis:7.0.10 restart: always volumes: - ./data/cache:/data rabbit: image: rabbitmq:3.11.8 restart: always ports: - 5673:5673 - 15672:15672 - 25672:25672 #? volumes: - ./data/rabbit/data:/var/lib/rabbitmq - ./data/rabbit/log:/var/log/rabbitmq web: build: . command: ["./wait-for-it.sh", "db:5432", "--", "uwsgi","--ini", "/code/config/uwsgi/uwsgi.ini"] restart: always volumes: - .:/code environment: - DJANGO_SETINGS_MODULE=my_project.settings.production - POSTGRES_BD=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres depends_on: - db - cache nginx: image: … -
ColumnForm object has no attribute 'instance'
I’m trying to submit a Column model, but it throws me an error when I clicked a submit button: the error: 'ColumnForm' object has no attribute 'instance' Forms.py: class ColumnForm(forms.Form): class Meta: model = Column fields = ['name', 'selec_type'] Models.py: class Column(models.Model): user = OneToOneFields (settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=100) selec_type = models.ForeignKey(Type, on_delete= models.CASCADE) Views.py: from django.views.generic.edit import FormView from django.forms import modelformset_factory from .forms import ColumnForm from .models import Column ColumnForm objects has no attribute instance class ColumnCreate(FormView): template_name = 'design.html' form_class = modelformset_factory(Column, form=ColumnForm, extra=30) success_url = '/' def form_valid(self, form): form.instance.user = self.request.user form.save() return super().form_valid(form) def form_invalid(self, form): return self.render_to_response(self.get_context_data(formset=form)) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['formset'] = context['form'] return context <form method='post'> {% csrf_token %} {{ formset.management_form}} {% for form in formset %} {{form.as_p}} {% endfor %} <button type='submit'>Save<button/> <form/> -
Django and Websocket giving an error index: WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/example/' failed:
I am following tutorial on django channels and I am getting an error that I can't solve. In web console this is displayed: index(16): WebSocket connection to 'ws://127.0.0.1:8000/ws/chat/example1/' failed: Here is settings.py: ASGI_APPLICATION = "core.routing.application" CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } routing.py file on project level: from channels.auth import AuthMiddlewareStack from channels.routing import ProtocolTypeRouter, URLRouter import anonymous.routing application = ProtocolTypeRouter({ 'websocket': AuthMiddlewareStack( URLRouter( anonymous.routing.websocket_urlpatterns ) ), }) asgi.py: import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') application = get_asgi_application() routing.py on app level: from django.urls import re_path from django.conf.urls import url from . import consumers websocket_urlpatterns = [ url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatRoomConsumer.as_asgi()), ] consumers.py: import json from channels.generic.websocket import AsyncWebsocketConsumer class ChatRoomConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] username = text_data_json['username'] await self.channel_layer.group_send( self.room_group_name, { 'type': 'chatroom_message', 'message': message, 'username': username, } ) async def chatroom_message(self, event): message = event['message'] username = event['username'] await self.send(text_data=json.dumps({ 'message': message, 'username': username, })) pass and chatroom.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link … -
Response Headers disappear after redirection - Django
I'm connecting an external auth system and a external permission system to my Django application (the auth will only be used in Django Admin and API, while the permission will be used for any request). Both systems are aready integrated and functional. But since this will only be available behind a VPC (which is not ready), my team need a mocked service in order to continue the mobile and frontend development. The mocked services are also using Django (I don't know about the real services because it's all proprietary software). The current flow is: Request hits Django's Admin. It checks if there's a session and if it's valid. If not, it checks for authorization headers (this should be coming from the Auth system) It there's neither, the user is redirected to the Mocked Auth login page. After submitting the login form, if it's valid, it'll redirect the user back to the Admin page, with a HTTP_TOKEN response header When accessing the request.headers in the admin view, there's no HTTP_TOKEN header or any other that contain the information I've just sent. I think this might be some kind of middleware that is overwriting this headers. mocked_auth/views.py class LoginView(LoginView): redirect_authenticated_user = True … -
Django If both product and variant models have color model, how to make Product tells which colors can variant has?
I have 4 models, product, variant and color. class Size(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Color(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Product(models.Model): title = models.CharField(max_length=100) description = models.TextField(max_length=400) colors = models.ManyToManyField(Color) sizes = models.ManyToManyField(Size) class Variant(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=10, validators=[MinValueValidator(Decimal('0.01'))]) quantity = models.IntegerField(validators=[MinValueValidator(0)]) color = models.ForeignKey(Color, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE) In this example a variant can have 1 product, 1 color and 1 size. The problem is the color and size are chosen among all the colors and sizes in the store. I want to limit the color and size in variant to the options of colors and size that were chosen in Product. If there anyway please let me know. Thank you :) -
Django messages not showing in certain views
I have multiple views in which I would like to show success messages when redirected home page after successful functions are performed. I have all the required settings added. I am rendering the views from a separate app to my main app, but all urls are referenced so there should be no issues there either. So I have no idea. My Registration view seems to render the message fine, but the rest don't. I will link the views below. WORKING def user_register(request): if request.method == "POST": form = UserRegisterForm(request.POST) if form.is_valid(): form.save() first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] email = form.cleaned_data['email'] username = form.cleaned_data['username'] password = form.cleaned_data['password1'] user = authenticate(username=username, password=password) Customer.objects.create(user=user,first_name=first_name, last_name=last_name, email=email) login(request, user) messages.success(request, "Registration successful, you are now logged in...") return redirect('home') else: register_form = UserRegisterForm() return render(request, 'registration/register.html', {'register_form': register_form}) NOT WORKING def user_login(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) messages.success(request,"You were successfully logged in...") return redirect('home') else: messages.success(request, ("There was an error logging in, please try again...")) return redirect('login') return render(request, 'registration/login.html', {}) def user_logout(request): logout(request) messages.info(request, ("You were successfully logged out...")) return redirect('home') HTML {% if messages … -
'TimeSlot' object is not iterable in Python Django
I have a list called time_slots. It contains objects of class TimeSlot. When I write return time_slots[0] I get an error - 'TimeSlot' object is not iterable. Can someone please help me with it? models.py class Room(models.Model): class Meta: ordering = ['number'] number = models.PositiveSmallIntegerField( validators=[MaxValueValidator(1000), MinValueValidator(1)], primary_key=True ) CATEGORIES = ( ('Regular', 'Regular'), ('Executive', 'Executive'), ('Deluxe', 'Deluxe'), ) category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular') CAPACITY = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), ) capacity = models.PositiveSmallIntegerField( choices=CAPACITY, default=2 ) advance = models.PositiveSmallIntegerField(default=10) manager = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE ) def __str__(self): return f'Number: {self.number}, category: {self.category}, capacity: {self.capacity}, advance: {self.advance}, manager: {self.manager}' class TimeSlot(models.Model): room = models.ForeignKey(Room, on_delete=models.CASCADE) available_from = models.TimeField() available_till = models.TimeField() def __str__(self): return f'Room: {self.room}, from: {self.available_from}, till: {self.available_till}' views.py def fun1(): # Some code print(time_slots) # [<TimeSlot: Room: Number: 4, category: Regular, capacity: 4, advance: 14, manager: anshul, from: 02:00:00, till: 04:00:00>, <TimeSlot: Room: Number: 1, category: Regular, capacity: 4, advance: 12, manager: anshul, from: 02:00:00, till: 05:00:00>] print(time_slots[0]) # Room: Number: 4, category: Regular, capacity: 4, advance: 14, manager: anshul, from: 02:00:00, till: 04:00:00 return time_slots[0] GitHub repo link -
Django Postgres- how to query jsonb[] in django
The model I'm trying to query has a jsonb[] field data and looks like this data = [{"id":"1","name":"abc","place":"def"},{"id":"2","name":"xyz","place":"uvw"}] I tried querying it using the solution listed here How to filter JSON Array in Django JSONField The query I'm running: name = MyModel.objects.filter( Q(data__contains=[{"name":"abc"}]) ) This query returns an empty query set. If I change data to [{"name":"abc"},{"name":"xyz"}] , then this query works How do I make this query work with all the keys in the json object? -
How to modify Python code to allow for more than two accounts in accounts.json file
Pastebin for the entire PY: https://pastebin.com/CiSnwSAv I have a accounts. Json file that works with the PY file, but as soon as I try to add more than 2 accounts in accounts.json, the py file gives me an error. The py file is suppose to paste email into the login page textbox. It does all it is suppose to but as the github repo states, it can work with upto 6 accounts, it doesn't work with 3. I hope my question is precise and understandable. accounts.json file works fine with 2 accounts [ { "username": "MY@gmail.com", "password": "12345678765" }, { "username": "MY@outlook.com", "password": "123213423" } ] and here is the part of the PY file that might me causing the issue def loadAccounts(): global ACCOUNTS if ARGS.accounts: ACCOUNTS = [] for account in ARGS.accounts: ACCOUNTS.append({"username": account.split(":")[0], "password": account.split(":")[1]}) else: try: ACCOUNTS = json.load(open("accounts.json", "r")) except FileNotFoundError: print("Please create an `accounts.json` file and try again.") prPurple(f""" [ACCOUNT] Accounts credential file "accounts.json" created. [ACCOUNT] Edit with your credentials and save, then press any key to continue... """) input() ACCOUNTS = json.load(open("accounts.json", "r")) But as soon as I add more than one account, [ { "username": "MY@gmail.com", "password": "34324214" }, { "username": "MY@outlook.com", … -
How do I change the menu sequence from "left to right" to "right to left" in backerydemo?
I can't change the menu sequence from "left to right" to "right to left"! This is need because our first language is Persian and we must read from right to left! I changed the languge in base.py to "fa-IR" and wagtail cms languges to "فارسی". But it didn't work. -
I recieved an already written django project that has worked previously on another machine but when I try to run it nothing happens
This is what happens PS C:\Users\***\Downloads\zapisy.zip\zapisy\zapisy-old\src\main python manage.py runserver PS C:\Users\***\Downloads\zapisy.zip\zapisy\zapisy-old\src\main> I just opened it in vscode, installed some python packets that were required and that's all I tried outputting any kind of error to file however the file came out empty