Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: conf.settings missing variables
It's recommended to import the settings module as such: from django.conf import settings My settings module structure is: ├── settings │ ├── base.py │ ├── dev.py │ └── prod.py I have a variable, amb, defined in base.py, which both dev.py and prod.py import from: from .base import * So how come when I do this in a test file: import django sys.path.append("/path/to/project/") os.environ.setdefault("DJANGO_SETTINGS_MODULE", "root_folder.settings.dev") # even when the above line is omitted django.setup() from django.conf import settings print(settings.amb) # or settings.AMB I get this error? AttributeError: 'Settings' object has no attribute 'amb' -
Heroku H13 error code! Can someone explain this?
I want to post file to heroku, the file that been uploaded is around 40mb,and when uploading is almost finished error happens: 2019-07-31T23:02:47.346551+00:00 heroku[router]: at=error code=H13 desc="Connection closed without response" method=POST path="/ML/create/" host=myapp.com request_id=2251b038-b0f6-4ecc-b722-13227f1bc2ba fwd="36.72.216.138" dyno=web.1 connect=0ms service=60006ms status=503 bytes=0 protocol=http -
Tried Replacing an image in my directory with different image, now nothing on my website is working
So basically I had a website made with Django that was working very well, loading css successfully from a bootstrap website template. I attempted to replace a image file in the project directory, a header background, with a different picture. The picture I created was the same format and dimensions exactly, but not the same file size if that matters. And of course I renamed it to the file I wanted to replace so that, what I assumed, Django would just start loading the new image since it was named the same as the old one. So that didn’t work. Nothing updated on any of my webpages, but the CSS and the old images were still loading fine. I tried a few solutions to fix the problem, and one of these made the problem much much worse. 1. I cleared my browser cache. 2. I ran the command: python manage.py collectstatic --noinput --clear - which seemed to fail but could have done something bad. 3. I put all of the original images back to where they should be. I could really use some help. Thanks ahead of time. -
Removing Secret Key from Heroku Git Repo
I have taken a project live with the help of Heroku. I set secret keys properly, using environment variables etc, not committing local settings containing any secret keys etc. Then, reviewing which actual files had been pushed to the git repo within Heroku, I found an 'old_settings'-file which in a pure oversight had been missed. That file contained the secret-key. I cleaned out the file and pushed the changes to the repo (git push heroku master). Then I deleted all past commits following the last answer: removing commit history in git Should this be fine? Reading Mipadis answer so it seems: Pushing secret keys to heroku, safe? Should this be a problem, or would this be considered problem solved? Appreciate any feedback, and should my English be confusing at all I'd be happy to clarify. -
Dealing with concurrency and other networking problems when building out a multiplayer game
I am building a game where 2 users move around on a canvas, with each having a trail, and if a user bumps into the other user's trail (or a wall) the user who bumped into the trail loses and the other user wins. The users move up/down/left/right by solving math problems. This will be an online multiplayer game. I'm finally getting to the point where I am building out the game (had been working mainly on the lobby, then quit, then started building the game again). But I am having issues with concurrency. For example, from both clients, I execute a function called generate_first_4_problems() which generates the first 4 problems for each client. This usually works but sometimes does not work. I have a function that populates the problem list for each user. It goes like: if user1.problem_list is already populated, populate user2.problem_list. These problems are generated on the backend and sent to the client (the problems are generated by the aforementioned generate_first_4_problems() -- it is runs twice). I forgot to mention, the reason why I think these are concurrency problems is: when I use the app in 2 different tabs (one regular, one incognito) or on my laptop … -
Getting Started with Square and Django
I'm trying to get a simple Square credit card form to work on our Django website. I'm new to using Square, but have used similar API's such as Stripe in the past. To start, I followed along with their Square Payment Form walkthrough. I added their SqPaymentForm library and our own javascript file where I initialized a new SqPaymentForm. The front-end appears to be working and is generating a unique card nonce every time I enter fake credentials. Next, I submitted the form to our back-end (including the card nonce, in a hidden nonce field). On the back-end, I've installed the Square Connect Python SDK. I copied their "Charge the card nonce" example as closely as possible, substituting our sandbox access token and location ID: import uuid import squareconnect from squareconnect.rest import ApiException from squareconnect.apis.transactions_api import TransactionsApi # create an instance of the Transactions API class api_instance = TransactionsApi() # setup authorization api_instance.api_client.configuration.access_token = 'sandbox-access-token' location_id = 'sandbox-location-id' nonce = request.POST.get('nonce', 'empty') if (nonce == 'empty'): print("Throw error") # print(nonce) try: # Charge idempotency_key = str(uuid.uuid1()) amount = {'amount': 100, 'currency': 'USD'} body = {'idempotency_key': idempotency_key, 'card_nonce': nonce, 'amount_money': amount} api_response = api_instance.charge(location_id, body) print (api_response.transaction) except ApiException as e: … -
How to remove user cart after order saved?django
I am trying to to build ecommerce website in which user is aforeignkey to cart and cart is unique for one order,but what happens is cart is connected to all orders when trying to remove from cart it removes items from all orders also adding to cart adds to all orders from this user what happen?i tried many solutions th separate cart and existing orders but all failed , any one can help and any suggestions for best relationships building? class Order(models.Model): user = models.ForeignKey(User,null=True, blank=True, on_delete=models.CASCADE) shipping_address = models.ForeignKey(Address, on_delete='CASCADE',related_name="shipping_address",null=True, blank=True) order_id = models.CharField(max_length=120, blank=True) cart = models.ForeignKey(Cart,on_delete=models.CASCADE) status = models.CharField(max_length=120, default="created", choices=ORDER_STATUS_CHOISES) shipping_total = models.DecimalField(default=5.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) active = models.BooleanField(default=True) date_posted = models.DateTimeField(default=timezone.now) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) products = models.ManyToManyField(Product, blank=True) total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) active = models.BooleanField(default=True) def checkout_home(request): cart_obj, cart_created = Cart.objects.get_or_create(user=request.user, active=True) order_obj = None if cart_created or cart_obj.products.count() == 0: return redirect("carts:home") login_form = LoginForm() address_form = AddressForm() shipping_address_id = request.session.get("shipping_address_id", None) # cart_obj=request.session['cart_id'] address_qs = None if request.user.is_authenticated: address_qs = Address.objects.filter(user=request.user) order_obj, order_obj_created = Order.objects.get_or_create(user=request.user, status='Created',cart=cart_obj) if shipping_address_id: order_obj.shipping_address = Address.objects.get(id=shipping_address_id) del … -
How to initialize class properties in inherited models
I have a very simple model: class Base (models.Model): class Meta: abstract = True class Foo(Base): model = None Field = models.CharField(max_length = 255) Field2 = models.IntegerField() def __init__(self, context = None, *args, **kwargs): self.Field = "Test string" self.model = context self.WorkingField = "Another test string" self.price = 1000 self.Field2 = 500 super().__init__(*args, **kwargs) Then I opened shell and tried to do some tests. I would like to initialize my class by calling constructor t = Foo(Bar) I expect that t.Field returns me a string value "Test string". Also I expect that t.Field2 returns me 500 result. Unexpectedly this property values are empty - the response in shell is an empty string ''. I suppose this problem has something to do with these property declarations Field = models.CharField(max_length = 255) I already tried: initialize a string property without declaration in class class Foo(Base): def __init__(self, context = None, *args, **kwargs): self.Field = "Test string" Everything works OK. But I have to create a database field for this property, so I want to declare it in model I try various combinations of super().init(). With params, without params. I tried to declare init method in the Base class of my model. Nothing … -
TypeError at /en/ string indices must be integers
I am getting started with Saleor and followed the installation for Windows. After running the server I am getting an error during template rendering that involves the menu.html and the shop.py files. @register.simple_tag def get_menu_item_name(menu_item, lang_code): translated = menu_item["translations"].get(lang_code) if translated: return translated["name"] return menu_item["name"] TypeError at /en/ string indices must be integers 11 {% get_menu_item_name lang_code=LANGUAGE_CODE menu_item=item %} 32 translated = menu_item['translations'].get(lang_code) File "C:\Users\kevin\Desktop\my_project\saleor\saleor\core\templatetags\shop.py", line 32, in get_menu_item_name translated = menu_item["translations"].get(lang_code) TypeError: string indices must be integers -
Django view function execution jumps to different function
I'm adding new applications to an existing Django project, and encountered something I am unable to debug. The callback error is "AttributeError: 'QuerySet' object has no attribute 'META'", but I'm not sure that's what's going on. I've written 4 of these apps for different API objects today, and had no issues. When I add print() debug messages to the functions, what I find is that the execution seems to be jumping out of my lead_lists view function and into my lists view function before it errors. This is my list.views.py def list(request): print("we're in lists view") lists = List.objects.all() print("lists saved for context") context = {'lists': lists} print("context created") return render(request, 'list.html', context) # fails here def load_lists(request): api_lists = services.get_lists() print("api lists loaded") db_list_ids = list(List.objects.values_list('list_id', flat=True)) # jumps out of function here print("db lists loaded") # this never prints print(f"db_list_ids: {db_list_ids}") for api_list in api_lists: if api_list['id'] not in db_list_ids: api_list = services.transform_list(api_list) form = ListModelForm(api_list) if form.is_valid(): form.save else: return HttpResponse(form.errors) print("exited load loop") lists = List.objects.all() print("load lists objects saved") context = {'lists': lists} print("load lists context saved") return render(request, 'load_lists.html', context) The expected result is, when I navigate to /list/load it runs the load_lists view … -
Why does my code work when I am playing against myself but not against other people?
For some reason, my code works when I log in to my game in one window and log in in an incognito window and I play the game with myself. A friend of mine wanted to help me test and none of our controls worked (like when I played against myself). The controls are up/down/left/right, and users must solve math problems to move. When solving math problems/moving when playing myself, things work fine. Solving math problems playing someone else, neither of us can move. I am using django-channels. Please help. Here is some of my code, let me know what else is needed: @channel_session_user def ws_receive_game(message): gamelabel = message.channel_session[u'gamelabel'] gamepk = gamelabel.split('-')[1] with transaction.atomic(): game = Game.objects.select_for_update().get(pk=gamepk) data = json.loads(message['text']) # set these to something to avoid # referenced before assignment error answer = [] level = [] operation = [] if u'level' in data: level = data[u'level'] if u'operation' in data: operation = data[u'operation'] if u'answer' in data: answer = data[u'answer'] if message.user.username != data[u'username']: return context = {} if message.user == game.creator: player_type = 'creator' elif message.user == game.opponent: player_type = 'opponent' def leave_game(): if player_type == 'creator': context['creator_left_game'] = True elif player_type == 'opponent': context['opponent_left_game'] = True … -
Django settings and html
can I change value in settings from true to false from html by using tags? and how? like I want to change AUTH_SYSTEM=True to AUTH_SYSTEM=False from html please -
What steps do I do for learning django?
I'm learning python from w3schools: 1. Is it completly tutorial?it means until the advansed? 2.After learning in this site , can I go for next step? 3.what is the next step(s)? 4.what things should I learn that can program front-end and back-end?(Please write down the steps in order of learning) 5.How I can understand that I learned python? 6.Before learnin django and ather frameworks of python,what things should I learn? Thanks! -
TypeError: object of type 'DeclarativeFieldsMetaclass' has no len()
I am trying to make a form in Django where the user inputs the name of a stock and I use it to fetch data from Yahoo Finance API. I have tried to do the same but am getting: TypeError: object of type 'DeclarativeFieldsMetaclass' has no len(). Help me out. PS- I'm new to coding models.py X = NameForm start = dt.datetime(2017, 1, 1) end = date.today() df = web.DataReader(X, 'yahoo', start, end) dates: List[str] = [] for x in range(len(df)): newdate = str(df.index[x]) newdate = newdate[0:10] dates.append(newdate) close = df['Close'] high = df['High'] low = df['Low'] volume = df['Volume'] R = ta.rsi(close, n=14, fillna=False) RSI = (R[-1]) class rsi(models.Model): status = "" if RSI <= 30: status = "Buy" elif RSI <= 15: status = "Buy" elif RSI >= 70: status = "Sell" elif RSI >= 85: status = "Sell" else: status = "Hold" forms.py class NameForm(forms.Form): Ticker = forms.CharField(label='Enter Ticker', max_length=100) views.py def get_ticker(request): if request.method == 'POST': ticker = NameForm(request.POST) if ticker.is_valid(): return index(request) else: ticker = NameForm() return render(request, 'SITE/form.html', {'ticker': ticker}) def index(request): r = "RSI is: ", rsi.status return HttpResponse(r) form.html form action="/ticker/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> … -
saving model and linking template to views.py
I cannot call the thanks-template after submitting data into contact-form. Why? The contact page repeat itself. Also no data is saved on database. What I am missing? Query of database in python-shell shows nothing is saved: Contact.objects.all() ###View.py def contact(request): if request.method == 'POST' : form = ContactForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] email = form.cleaned_data['email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] form.save() return render ('thanks.html', {'name' : name, 'email' : email, 'subject' : subject, 'message' : message}) else: form = ContactForm() return render(request, 'contact.html', {'form':form}) ###models.py from django.db import models class Contact (models.Model): name = models.CharField (max_length=100) email = models.EmailField (max_length=100) subject = models.CharField (max_length=100) message = models.CharField (max_length=100) ###forms.py from django import forms from .models import Contact class ContactForm (forms.ModelForm): class Meta: model = Contact fields = ['name', 'email', 'subject', 'message'] ###urls.py urlpatterns = [ path('', views.index, name='index'), path('contact', views.contact, name='contact'), path('thanks', views.thanks, name='thanks'),] ###contact.html <body> <div class="container"> <br /> <form action="contact" method="post"> {% csrf_token %} ... ###thanks.html <body> <div class="container"> <br /> <form action="contact" method="post"> {% csrf_token %} ... -
View with more than one button redirecting to different pages
I have a View (I use FormView) that will render a dropdown option. When I select an option, an Ajax function populate the rest of the Form. After the datas are shown, the user can press different buttons to redirect to other pages. For now, I want just 2 buttons. But I don't know how to do this, I've tried some codes and got nothing, not even got redirect to other page. The first page are "Teste" and the buttons need to redirect to "identificacao", or "mapa". Here are my following code urls.py: path('teste', views.TesteView.as_view(), name="teste"), path('identificacao', TemplateView.as_view(template_name = 'solid/identificacao.html'), name="identificacao"), path('mapa', views.MapaView.as_view(), name="mapa") view.py: class DutosView(generic.FormView): # FormView precisa ser relacionada a um Model. Mesmo que não use ao longo do # programa a variável "model", como é o caso presente. template_name = 'solid/teste.html' form_class = Dutos # success_url = 'solid/mapa.html' # success_url = reverse_lazy('mapa') success_url = '/mapa/' def form_valid(self, form): nomeDuto = form.cleaned_data['nomeDuto'] codigoDuto = DUTO.objects.values_list('DU_CD_ID_Duto',flat = True).filter(DU_DS_Nome_Do_Duto = nomeDuto) self.request.session['nomeDuto'] = nomeDuto latlongs = PIG.objects.values_list("PI_VL_Latitude","PI_VL_Longitude").filter(PI_CD_ID_Duto = codigoDuto) latlongs = [[float(x[0]),float(x[1])] for x in latlongs] latitudeIni = latlongs[0][0] longIni = latlongs[0][1] self.request.session['latlongs'] = latlongs self.request.session['latitudeIni'] = latitudeIni self.request.session['longIni'] = longIni return super().form_valid(form) # I've tried the code above … -
How to make all celery tasks log into one file
I have Django application with such logging configuration. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '%(asctime)s [%(levelname)s] %(filename)s:%(lineno)s: %(message)s' }, }, 'handlers': { 'cron': { 'class': 'logging.FileHandler', 'filename': 'cron.log', 'formatter': 'default', }, 'admin': { 'class': 'logging.FileHandler', 'filename': 'admin.log', 'formatter': 'default', }, 'app': { 'class': 'logging.FileHandler', 'filename': 'app.log', 'formatter': 'default', }, 'core': { 'class': 'logging.FileHandler', 'filename': 'app.log', 'formatter': 'default', }, 'metrics': { 'class': 'logging.FileHandler', 'filename': 'metrics.log', 'formatter': 'default', }, 'pixel': { 'class': 'logging.FileHandler', 'filename': 'pixel.log', 'formatter': 'default', }, }, 'loggers': { 'cron_api': { 'handlers': ['cron'], 'level': 'DEBUG', }, 'main': { 'handlers': ['app'], 'level': 'INFO', }, 'admin': { 'handlers': ['admin'], 'level': 'INFO', }, 'spa_api': { 'handlers': ['app'], 'level': 'INFO', }, 'metrics': { 'handlers': ['metrics'], 'level': 'INFO', }, 'pixel': { 'handlers': ['pixel'], 'level': 'INFO', }, }, } I'd like all celery tasks write to worker (it's executed at) .log file. Is there a way of defining it without creating specific logger for every task? So, instead of writing 'loggers': { 'main.celery_tasks.task1': { ... } } write something like 'loggers': { 'celery': { ... } } Or just define a file when starting worker (with -f param). -
Django Allauth, Twitter Scope
I'd like to get the user email from the twitter oauth. So I requested this in the app settings. I added the scope (to settings.py): SOCIALACCOUNT_PROVIDERS = { 'linkedin': { 'SCOPE': [ 'r_emailaddress', 'r_basicprofile', 'r_fullprofile', ], 'PROFILE_FIELDS': [ 'id', 'first-name', 'last-name', 'positions', 'email-address', 'picture-url', 'public-profile-url', 'headline', 'skills', 'summary', 'location', 'industry', 'positions', 'company', 'specialties', 'public-profile-url', ], 'LOCATION_FIELDS': [ 'location', ], 'POSITION_FIELDS': [ 'company', ] }, 'twitter': { 'SCOPE': ['email'], }, } However, I'm still having the user data like the name, picture ..etc but not the email. Any suggestion ? -
User profiles not being created at sign up
It seemed to be working quite well over the past few days but, since adding follow functionality, profiles are not created when they sign up. I read through the other questions like this one and I see things about using @reciever, do we have to use receivers? I followed a tutorial on how to allow profile creation at the time of sign up, the line goes as follows User.profile = property(lambda u: CustomUserProfile.objects.get_or_create(user=u)[0]) It's in my models.py but not inside of a function nor the profile class, is that my mistake or do we really have to use receivers? Forgive me, I've been teaching myself through tutorials and docs but alot of tutorials were deprecated (and I had no idea) so I just went off on my own and now i'm regretting it. -
How to get / or create a taggit model for each related model?
I want to use taggs, but I have something to do something like: To get all tags added only in Post instances: post_tags.objects.all() To get all tags added only in Snippet instances: snippet_tags.objects.all() How can I do this? -
ModuleNotFoundError: No module named 'ethereum' in django Metamask installation
Now, I'm trying a work for django and metamask connection. But while I tried to runserver, I faced with ... urlconf_module = import_module(urlconf_module) File "C:\Users\Emma\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Emma\Desktop\web3start\web3auth\urls.py", line 3, in <module> from web3auth import views File "C:\Users\Emma\Desktop\web3start\web3auth\views.py", line 10, in <module> from web3auth.forms import LoginForm, SignupForm File "C:\Users\Emma\Desktop\web3start\web3auth\forms.py", line 8, in <module> from .utils import validate_eth_address File "C:\Users\Emma\Desktop\web3start\web3auth\utils.py", line 2, in <module> import ethereum ModuleNotFoundError: No module named 'ethereum' ... So I tried a command such as pip install ethereum, pip install -r requirements.txt, pip install 'rlp==0.6.0' but still error comes out. Anyone can help me with this? -
How to determine if I am currently inside a Redis Task Worker
if i have a function def I_TAKE_A_LONG_TIME(): if I_AM_RUNNING_IN_A_REDIS_WORKER: # do something special # do some stuff that takes a while from rq.job import Job @Job('default') def worker(): return I_TAKE_A_LONG_TIME() sometimes this is called directly, I_TAKE_A_LONG_TIME() other times it is called via worker.delay() (redis task stuff) is there a builtin redis way to tell if I_TAKE_A_LONG_TIME is being run in a task worker vs being run directly? get_current_job() I think returns any the current running job (not necessarily this running job) -
django panda read sql query map parameters
I am trying to connect sql server database within django framework, to read sql query result into panda dataframe from django.db import connections query = """SELECT * FROM [dbo].[table] WHERE project=%(Name)s""" data = pd.read_sql(query, connections[database], params={'Name': input} ) the error message I got is 'format requires a mapping' if I do it something like below, it will work, but I really want to be able to map each parameter with names: from django.db import connections query = """SELECT * FROM [dbo].[table] WHERE project=%s""" data = pd.read_sql(query, connections[database], params={input} ) I was using odbc driver 17 for sql server -
Klaviyo Form shows twice on homepage
I embedded a klaviyo form on shopify and it showed twice on the homepage of the shop I'm working on. I'm quite new to shopify development but know django and a little rails but still get confused on reading codes. <div class="homepage-page {{ section.settings.homepage_page_color }}" data-section-id="{{ section.id }}" data-section-type="index-page"> <div class="klaviyo-form-LLvHeC"></div> {% for block in section.blocks %} <div class="wrapper"> <div class="grid"> {% case block.type %} {% when 'page' %} {% if block.settings.home_page_content != blank %} {% assign page = pages[block.settings.home_page_content] %} {% assign page_src = page.content | escape %} {% if page_src contains '&lt;img' %} {% assign homepage_page_grid = 'one-whole' %} {% else %} {% assign homepage_page_grid = 'large--five-sixths push--large--one-twelfth' %} {% endif %} <div class="grid__item {{ homepage_page_grid }}"> {% if block.settings.home_page_show_title %} <h4 class="home__subtitle">{{ page.title }}</h4> {% endif %} <div class="rte homepage-page__content"> {% unless page == blank or page.empty? %} {{ page.content }} {% else %} {{ 'home_page.onboarding.no_content' | t }} {% endunless %} </div> </div> {% endif %} {% when 'text' %} <div class="grid__item large--five-sixths push--large--one-twelfth"> <div class="rte homepage-page__content"> {% if block.settings.home_page_richtext != blank %} {{ block.settings.home_page_richtext }} {% else %} {{ 'home_page.onboarding.no_content' | t }} {% endif %} </div> </div> {% else %} {% endcase %} </div> … -
Adding a Sold Out option to price field in Django
at present I have a basic shop with a price model defined as a decimal field. price = models.DecimalField(max_digits=10, decimal_places=2) I'd like to be able to keep products visible but add a sold out option. Is there a way to allow this field to include a blank price or a Sold Out option? I had also tried adding another model field that would be tested for truth and displaying sold out otherwise, but this didn't end up showing in template. Here, my idea was: soldout = models.BooleanField(defualt = False) and in the template: {% if product.soldout %} <button type="button" class="btn btn-danger">SOLD OUT!</button> Thanks!