Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework api testing returns empty result
I am trying to make testing on Django Rest Framework API. When i test URLs manually i get all kind of data which i want, but when i test it by APITestCase it returns empty results, in detail API page it returns "not found" error. This is code: class UsersTest(APITestCase): def setUp(self): self.url = reverse('user:user-list') def test_fetch_users(self): response = self.client.get(self.url) response_data = json.loads(response.content) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue(response_data.get('results')) def test_fetch_users_date_intervals(self): date_from = '2019-10-14' date_to = '2019-10-20' response = self.client.get(self.url, {'from': date_from, 'to': date_to}) response_data = json.loads(response.content) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertTrue(response_data.get('results')) Thanks -
make a bussines installer for python project
I develope a Django offline project. now I want to release it. I need to make an installer that makes these changes in my customer side: install python install Django install packages and libraries as requirements (also PostgreSQL) make a desktop shortcut and something important is that I want to make a short cut that customer run it, Django server run automatically without needed to command 'python run manage.py' is there any idea about that? -
Error : django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. while deploying app to heroku
I'm a beginner trying to deploy my first Django project using Heroku, but now stuck with the empty SECRET_KEY problem when I run the git push master heroku command: Checked with local machine but my app running in local machine without any problem. I've checked Other solutions on this site none of them seems helping me. Here is the error remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 224, in fetch_command remote: app_name = commands[subcommand] remote: KeyError: 'collectstatic' remote: During handling of the above exception, another exception occurred: remote: Traceback (most recent call last): remote: File "manage.py", line 21, in <module> remote: main() remote: File "manage.py", line 17, in main remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 231, in fetch_command remote: settings.INSTALLED_APPS remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 76, in __getattr__ remote: self._setup(name) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 63, in _setup remote: self._wrapped = Settings(settings_module) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/conf/__init__.py", line 161, in __init__ remote: raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") remote: django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. remote: remote: ! Error while running '$ … -
Get user object model that is being changed Django Admin
How do you retrieve the model of the user that is currently being changed using the Django admin? For example you have the change url: https://www.example.com/admin/users/2/change I need the user model with the id 2, not the currently logged in user that is found by performing self.request.user -
How to change the datetime field with many objects?
I want to change my datetime field but current_user_moneybooks has many objects. so i want to know is there any method to change the format of datetime field. I tried link: for current_user_moneybook in current_user_moneybooks def start_date(self): return self.start_date.strftime("%Y-%m-%d") def end_date(self): return self.end_date.strftime("%Y-%m-%d") or def all_moneybooks(request): current_user = request.user if current_user.is_authenticated: current_user_moneybooks = current_user.owner.all start_date.strftime("%Y-%m-%d") for current_user_moneybook in current_user_moneybooks end_date.strftime("%Y-%m-%d") for current_user_moneybook in current_user_moneybooks return render(request, "home.html", context={"current_user": current_user, "all_moneybooks": all_moneybooks, "current_user_moneybooks": current_user_moneybooks}) else: return render(request, "home.html", context={"current_user": current_user, "all_moneybooks": all_moneybooks}) and result : start_date.strftime("%Y-%m-%d") for current_user_moneybook in current_user_moneybooks ^ SyntaxError: invalid syntax -
unable to import Django.shortcuts
I was working on my first django project using the documentation. I am getting this error while importing django modules. I'm sure that django is successfully installed in my virtual environment. The error is: CLICK TO GET THE SCREENSHOT OF THE ERROR Unable to import 'django.shortcuts' Unable to import 'django.http' Unable to import 'django.contrib' Unable to import 'django.urls' -
Django - creating an CRM like app makes me trouble
I would like to create an app which will help generate offers. Let's assume I have two apps in Django project: offers which allows to: display offers list, creating the new ones and updating an existing offer. warehouse which allows to: display all goods added to warehouse, creating new ones, and updating existing goods. During creating new offer I want to have a possibility to add some of the warehouse goods to the offer and set some additional parameters like: price, quantity and so on to print it on the offer. I want to achieve this using Bootstrap modal pop-up. How should my models, and views files looks like to achieve this? Should I use Many to Many relation ? P.S. I am not sure if You even understand my doubts :D -
How to host a Django and Nuxt application online
i have created a web application using Django for the Back-end and Nuxt.js as the front-end frame work, and i don't know how i can host the web app online. i have tried using python anywhere but they don't have support for node severs. -
Run manage.py shell_plus --print-sql in Pycharm Django Console
Is there a way to configure Pycharm Django Console to run shell_plus from django_extensions? In particular, I want to print the SQL for every ORM operation. I've tried this script, passing the print_sql options, but its not working. Thank you in advance. import sys import django sys.path.extend([WORKING_DIR_AND_PYTHON_PATHS]) if 'setup' in dir(django): django.setup() import django_manage_shell; django_manage_shell.run(PROJECT_ROOT) from django_extensions.management import shells from django.core.management.color import color_style style = color_style(force_color=True) # Default settings for shell_plus shell_plus_default_settings = { 'ipython': True, 'print_sql': True, } g = globals() objects_to_import = shells.import_objects(shell_plus_default_settings, style) g.update(objects_to_import) print(style.NOTICE("Python %s on %s" % (sys.version, sys.platform))) print(style.NOTICE("Django %s" % django.get_version())) print(style.SUCCESS("Shell Prepared. Enjoy!")) -
Django column does not exist error when created a mixed-case or upper-case column name
class uretimkaynaklari(models.Model): tarih = models.DateField() malzemeNo = models.CharField(max_length=30) operasyonKodu = models.CharField(max_length=30) isyeri = models.CharField(max_length=30) vardiya = models.CharField(max_length=30) sicil = models.CharField(max_length=30) uretimMiktari = models.FloatField() uretimSuresiMakina = models.FloatField() uretimSuresiIscilik = models.FloatField() def __str__(self): return self.sicil def operatoranalizi_func(request): cursor = connection.cursor() cursor.execute("""SELECT id as id, tarih as tarih, sicil as sicil, uretimsuresimakina as uretimSuresiMakina FROM operatoranalizi_uretimkaynaklari """) rows = cursor.fetchall() print(rows) return HttpResponse("success") when ı get only "id", "tarih", "isyeri" columns everything is ok but when ı want to get "uretimsuresimakina" column ı got error column does not exist. -
unable to display images from model usingo django
in settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'pictures') MEDIA_URL = '/pictures/' in models.py class Campaign(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # this is many to one relationship, on_deleting user, profile will also be deleted campaign_title = models.CharField(max_length=200, blank=True) campaign_image = models.ImageField(default="default_campaign.png",upload_to="campaign_pictures") in views.py def landing_page(request): campaigns = Campaign.objects.all().order_by('-id') print(campaigns) return render(request, 'core/landing_page.html',{'campaigns':campaigns}) in landing_page.html {% for campaign in campaigns %} <img src="{{campaign.campaign_image.url}}"> {% endfor %} issue if file name is abc xyz.jpg, it gets saved into /pictures/campaign_pictures as abc_xyz.jpg in html template, the src of image should be '/pictures/campaign_pictures/abc_xyz.jpg' but it shows only '/pictures/abc%20xyz.jpg' -
Django canot locate my static files directory
Hey Guys, I have a problem, django canot find my static files when testing the page. Google Console errors, *127.0.0.1/:10 GET http://127.0.0.1:8000/static/css/all.css net::ERR_ABORTED 404 (Not Found) and many other errors like that My static files in settings.py; STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATIC_FILES_DIRS = [ os.path.join(BASE_DIR, 'btre/static') ] my static files are properly, i mean double checked, in my project folder (i.e. btre/static/) did collect static command in manage.py but still getting errors. I also properly referenced the CSS and JS files in base.html as well; {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Font Awesome --> <link rel="stylesheet" href="{% static 'css/all.css' %}"> <!-- Bootstrap --> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <!-- Lightbox --> <link rel="stylesheet" href="{% static 'css/lightbox.min.css' %}"> <!-- Custom --> <link rel="stylesheet" href="{% static 'css/style.css' %}"> -
Django I Want to pass multiple ids and get their data. Scenario : Social Network system
This is a code for getting all the followers for a specific id, then passsing those ids to then get all their posts/activities from another table. But I can't seem to get that. @api_view(['GET']) def build_ecosystem(request, id): """ 1. first get all objects that follow the given id 2. find all the activities posted by all those ids 3. form a payload """ list_of_followers,ecosystem_activities = [], [] def get_object(id): try: return startup_activities.objects.filter(stup=id) except startup_activities.DoesNotExist: raise Http404 def get_joined_eco_objs(id): try: return follows.objects.filter(ceo_id__exact=id) except startup_activities.DoesNotExist: raise Http404 if request.method == 'GET': sd = get_joined_eco_objs(id) serializer = FollowerFollowingSerializer(sd, many = True) the_list = serializer.data for an_item in the_list: list_of_followers.append(an_item["stup_follows"]) for x in range(len(list_of_followers)): ecosystem_activities = StupActivitiesSerializer(startup_activities.objects.filter(stup=list_of_followers[x],many = True)) return Response(ecosystem_activities.data) But when I pass the id I get: [] Help. -
How to test if an instance has a subclass with ForeignKey pointing to it in Django?
I'm new with Django and I woul like to know if the instance of Market I'm working on has a t least on object of class Candle pointing to it. As you can see in my code the relation between Market and Candle has null=True so it's optional. How can I perform this check? models.py: class Market(models.Model): pair = models.CharField(max_length=12, null=True) def __str__(self): return str(self.pair) class Candle(models.Model): market = models.ForeignKey(Market, on_delete=models.CASCADE, related_name='market', null= True ) dt = models.DateTimeField(unique=True) def __str__(self): return str(self.dt.strftime("%Y-%m-%d %H:%M:%S")) I tried many things but everytime it throw an error. if instance.Candle().exists(): ... if Candle(market=instance).exists(): ... Thank you -
How to print out and use list variable(using groupby)
def moneybook_detail(request, pk): moneybook = moneybook_models.Moneybook.objects.get(pk=pk) moneylogs = moneybook.moneylog_set.all() def extract_pay_day(moneylogs): return moneylogs.pay_day.date() same_day_pays = moneylogs.order_by("pay_day") for pay_day, group in groupby(same_day_pays, key=extract_pay_day): print(pay_day, list(group)) I don't know loop exactly meaning of this line...just typing with stackoverflow. then I can get below query. 2020-01-09 [] 2020-01-12 [, , , , ] How can I use this query in html? which variable do I have to use? Like: {{same_day_pay.pay_day}} {% for same_day_pay in same_day_pays %} {{same_day_pay.memo}} / {{same_day_pay.price}} {% endfor% } -> result 2019.01.03 pay1 / 120 pay2 / 200 2019.01.02 pay0 / 100 I think this is easy question I guess. but I'm very confusing. hope your kindly help please. -
How can I search variables from another template
I am in my homepage template where I have only search box like google main search page looks like, Now I want to search variables from another template and display it but nothing happen. Below is my code Homepage template <form action="{% url 'loststuffapp:IndexView' %}" method="GET" value="{{request.GET.q}}" class="navbar-form" role="search" style="margin-left: 25em;"> <input type="text"placeholder="Search....." name="q"> <button type="submit" onclick="/Miscellaneous"><i class="fa fa-search"></i></button> </form> Home page view def IndexView(request): title="Homepage" return render(request, "loststuffapp/home.html", {"title":title}) Miscellaneous template <div class="card-body"> <p><label style="font-size:15px; font-weight: bold;color: black;">Jina la nyaraka: </label>{{Doc.docs_name}}</p> <p><label style="font-size:15px; font-weight: bold;color: black;">Aina ya nyaraka: </label>{{Doc.item_type}}</p> {% if Doc.image %} <div class="row"> <div class="col-md-12"> <img class="img-fluid" alt="Responsive image" src ="{{Doc.image.url}}" style="display: flex;" /> </div> </div> {% endif %} <p>{{Doc.date}}</p> </div> Miscellaneous view def Miscellaneous(request): query = request.GET.get('q', '') qsets=(Q(docs_name__icontains=query)|Q(item_type__icontains=query)) return render(request, "loststuffapp/Miscellaneous.html", context={"documents":Documents.objects.filter(qsets)}) -
Can't make Django ModelForm Select Choice Field work in Template
I tried multiple solutions around but couldn't make my select field work in Django Template. I am beginner and humbly apologize if my question is not up to standard. My select button is not showing any options in django form. I only have two options to show. Is there anyway I can get form field without having iterate through it in template? Using Django 3 and Python 3.8. Help will be much appreciated. Model: class User(AbstracUser): ACC_TYPE = (('Student', 'Student'), ('Teacher', 'Teacher')) role = models.CharField(max_length=100, choices=ACC_TYPE ..... Form: class UserForm(UserCreationForm): #Using django's default form account_type = forms.CharField(widget=forms.Select(choices=User.ACC_TYPE)) model = User fields =('............., 'account_type') def __init__(self, *args, **kwargs): super(UserCreationForm, self).__init__(*args, **kwargs) self.fields['account_type'].choices = [(each[0], each[1]) for each in User.ACC_TYPE] self.fields['account_type'].required = True Template: ....... <select> {% for opt, val in form.account_type.choices %} <option value="{{ opt }}">{{ value }}</option> {% endfor %} </select> ...... -
ImportError at / No module named 'storages' when i try to load with gunicorn but working in local
ImportError at / No module named 'storages' Request Method: GET Request URL: http://example.com/ Django Version: 2.2.5 Exception Type: ImportError Exception Value: No module named 'storages' Exception Location: in _find_and_load_unlocked, line 956 while trying to connect amazon s3 below mentioning s3 settings if USE_S3: AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID', default='') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY', default='') AWS_STORAGE_BUCKET_NAME = config('AWS_STORAGE_BUCKET_NAME', default='') AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} AWS_LOCATION = 'static' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') also ive did pip install django-storages pip install boto3 -
Can I use Django's template to launch react JS?
I found difficult to use Django Rest API with React JS as I am newbie (easy to make CRUD operation found difficult to handle user authentication ). Can I use regular Django (not Django Rest framework ) templates to render the react JS ? I will user webpack to mount the Javascript file and hook it with Django templates -
How to render MathJax dynamically without div id?
I am trying to render MathJax dynamically using django-pagedown. However, most code such as this- $(".edit").click(function(){ $(".math-tex").each(function(index){ $(this).html("\\(" + $(this).find("script").html() + "\\)"); }); $("#fullarticle").attr("contenteditable", "true"); CKEDITOR.inline('fullarticle'); }); $(".save").click(function(){ $("#fullarticle").attr("contenteditable", "false"); for(k in CKEDITOR.instances) { var instance = CKEDITOR.instances[k]; instance.destroy(); } MathJax.Hub.Queue(["Typeset",MathJax.Hub]); }); -require you to have a div id or span class, etc. How would I make it so that JavaScript renders dynamically without a unique ID in Django? -
reset imagefield to default image using if condition django
my profile form has two halves: individual and NGO (ngo part of form has imagefield). the user can switch between the profile types. if user switches from NGO to individual, i update the ngo related fields to NA in my function. However, i need to reset the image field associated with NGO to default and delete the image. models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) # on_deleting user, profile will also be deleted image = models.ImageField(default="profilepic.jpg",upload_to="profile_pictures") profile_type = models.CharField(max_length=20,choices=PROFILE_TYPES, default='individual') dob = models.DateField(null=True) bio = models.TextField(null=True) anonymous = models.BooleanField(default=False) ngo_name = models.CharField(max_length=200, blank=True) ngo_address = models.CharField(max_length=200, blank=True) ngo_phone = models.CharField(max_length=200, blank=True) ngo_registration_num = models.CharField(max_length=200, blank=True) ngo_registration_cert = models.ImageField(default="default_ngo.png",upload_to="ngo_documents") ngo_status = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return f'{self.user.username} Profile' forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['image','profile_type','dob','bio','anonymous','profile_type','ngo_name','ngo_address','ngo_phone','ngo_registration_num','ngo_registration_cert','ngo_status'] views.py @login_required def profile_edit(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): if p_form.cleaned_data.get('profile_type') == 'ngo': u_form.save() p_form.save() messages.success(request, f'your profile has been updated as NGO ') return redirect('users:profile') else: u_form.save() temp_p_form = p_form.save(commit=False) temp_p_form.ngo_name = 'NA' temp_p_form.ngo_address = 'NA' temp_p_form.ngo_phone = 'NA' temp_p_form.ngo_registration_num = 'NA' temp_p_form.ngo_phone = 'NA' temp_p_form.ngo_status = False temp_p_form.ngo_registration_cert = NEED TO SET THIS TO … -
Django Channels or Redis or Daphne for chat application?
Todays Im Working on a Chat Application for my project with Django Website WSGI's is already created but now the project manager says we need a chat i research a lot for this work and i realized that i need a ASGI and Websocket's to This Work But I Dont Know Whats The Best Way to Do This Job It Should Easy to Learn and Use High Maintaice and Documentation What Are You Suggest for Me ? Channels | redis | or another ? -
how to return multiple anchor by format_html in django
what currently i have is : def Action(self, obj): return format_html( '<a class="button" title="View" href="view/{}"><i class="fa fa-eye" aria-hidden="true"></i></a>&nbsp;' '<a class="button delete_vehicle trash-icon" title="Delete" data-id="{}" href="delete/{}"><i class="fa fa-trash" aria-hidden="true"></i></a>', (obj.id), (obj.id), (obj.id), But i am trying to pass three html it not retuning me the third anchor .. return format_html( '<a class="button" title="View" href="view/{}"><i class="fa fa-eye" aria-hidden="true"></i></a>&nbsp;' '<a class="button delete_vehicle trash-icon" title="Delete" data-id="{}" href="delete/{}"><i class="fa fa-trash" aria-hidden="true"></i></a>', '<a class="button edit" title="edit" data-id="{}" href="edit/{}"><i class="fa fa-edit" aria-hidden="true"></i></a>', (obj.id), (obj.id), (obj.id), (obj.id), why i am not getting this can anyone please help me in related this.how can i pass or return three anchor. -
How to Add extra context for Class Based Login View?
I was previously using Django==2.0.6 now I want to upgrade it to Django==2.2.3. And Doing some research I get to know that In django-2.1, the old function-based views of login, logout have been removed. I still want to add some extra context to LoginView as per my project requirement.. Previously using Function Based View I have done the following: from django.contrib.auth.views import login as auth_views_login def login(*args, **kwargs): """ Auth Login View """ ecom_company = Ecom_Company.objects.filter(pk=1).first() landing_details = Landing.objects.filter(company=ecom_company).first() category_list = Categories.objects.filter( company=ecom_company).exclude(name__exact='Lab Test').order_by('id') partners_list = Partners.objects.filter( company=ecom_company).order_by('-id') stock_list = StockItem.objects.filter( organisation=ecom_company.organisation).order_by('id') context = { 'ecom_company': ecom_company, 'landing_details': landing_details, 'category_list': category_list, 'partners_list': partners_list, 'stock_list': stock_list } return auth_views_login(*args, extra_context=context, **kwargs) And in urls: url(r'login/$', views.login, {'template_name': 'login.html'}, name="login"), How do I pass the extra context for Class Based Login View as because Django==2.2 does not support the above. -
Gunicorn Failed to start Service (Unknown section 'Service'. Ignoring.)
I am setting up Django Project on Digital Ocean with Nginx. I am getting error on journalctl -u gunicorn.socket this command. Got this Error ** root@vavaphysio:/var/www/html/sandbox# journalctl -u gunicorn.socket -- Logs begin at Mon 2020-01-06 03:17:11 UTC, end at Sat 2020-01-18 06:28:38 UTC. -- Jan 14 12:08:43 vavaphysio systemd[1]: /etc/systemd/system/gunicorn.socket:6: Unknown section 'Service'. Ignoring. Jan 14 12:08:43 vavaphysio systemd[1]: gunicorn.socket: Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing. Jan 16 09:04:14 vavaphysio systemd[1]: Listening on gunicorn socket. Jan 16 09:36:44 vavaphysio systemd[1]: gunicorn.socket: Failed with result 'service-start-limit-hit'. Jan 16 09:53:47 vavaphysio systemd[1]: Listening on gunicorn socket. ** Here is my gunicorn Socket file **[Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target** Gunicorn Service File: **[Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=www-data WorkingDirectory=/var/www/html/sandbox ExecStart=/var/www/html/sandbox/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ sandbox.wsgi:application [Install] WantedBy=multi-user.target** Any Answer Please.