Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Errors not being logged to txt file
Hi have the following code in my setting.py file. Upon a 500 error, an email gets sent out with the details of the error, an error.txt file gets created in the directory noted below, but the txt file is empty. No errors are being written to this txt file. Any thoughts? LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, 'file': { 'level': 'ERROR', 'class': 'logging.FileHandler', 'filename': '/home/jasonhoward/webapps/myproject/jason/errors.log' }, }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, }, 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': False, }, } } -
Performing calculation in a one to many relationship
I have two models and I try to subtract the value of one field with the other when a form is updated. The fields are in separate models, I have a form that is used to save the changes made to NewLeave model and I want to be able to subtract the value of Leave_current_balance in Leave_Balance model with the Total_working_days in the NewLeave model and save the update Leave_current_balance value. Currently, when the form is updated I want to call the calculateBalance method which performs the calculation but it is not working. class Leave_Balance(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, ) Outstanding_balance = models.FloatField(null=True, blank=True, default=None) Monthly_entitlement = models.FloatField(null=True, blank=True, default=None) Monthly_consumption = models.FloatField(null=True, blank=True, default=None) Leave_current_balance = models.FloatField(null=True, blank=True, default=None) class NewLeave(models.Model): user = models.ForeignKey(User, default='', on_delete=models.CASCADE) leave_balance = models.ManyToManyField(Leave_Balance) Total_working_days = models.FloatField(null=True, blank=False) def unitDirectorForm(request, staffs_id): if request.method == 'POST': getstaffid = NewLeave.objects.get(id=staffs_id) form = DirectorForm(request.POST, instance=getstaffid) if form.is_valid(): calculateBalance(getstaffid) form.save() return HttpResponse('You have successfully Authorise the leave') else: getstaffid = NewLeave.objects.get(id=staffs_id) form = DirectorForm(instance=getstaffid) return render(request, 'director_authorize_form.html', {'form': form}) def calculateBalance(staff_id): update_balance = staff_id update_balance.leave_balance.Leave_current_balance = update_balance.leave_balance. Leave_current_balance - update_balance.Total_working_days update_balance.save() -
Failing to find views when using slugs and class based views
One of my Django apps, "Pages", has many different classes in the models.py. Each of them have a slug attribute/field of their own. I'm able to load the URL for the first - "company" (first class) but for some reason can't load the other URLs. I have tried importing the views separately and creating urls paths for each view. When doing this, only the last URLs (third one) would load. models.py class Industry(models.Model): industry = models.CharField(max_length=140, null=True, blank=True, unique=True) slug = models.SlugField(max_length=40, null=True, blank=True) def __str__(self): return self.industry def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.industry) super(Industry, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('industry_detail', args=[(self.slug)]) class Subindustry(models.Model): subindustry = models.CharField(max_length=140, null=True, blank=True, unique=True) industry = models.ForeignKey( Industry, on_delete=models.CASCADE, related_name='ParentIndustry', ) slug = models.SlugField(max_length=40, null=True, blank=True) def __str__(self): return self.subindustry def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.subindustry) super(Subindustry, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('subindustry_detail', args=[(self.slug)]) class Company(models.Model): name = models.CharField(max_length=50, blank=False, unique=True, default=(str(id))) website = models.URLField(max_length=100) ... slug = models.SlugField(max_length=40, null=True, blank=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.name) super(Company, self).save(*args, **kwargs) def get_absolute_url(self): return reverse('company_detail', args=[(self.slug)]) views.py from django.views.generic import DetailView from django.urls import reverse_lazy # Create your views … -
how to handle this syntax error in django project
I have transferred my Django project onto Linode server already. The project was developed in VS, within anaconda (base) environment on my Mac. After I downloaded it onto the Linode server when activating it, it gave me too many dependencies (not all needed it seemed). One of them prevented me from completing the process. So, I sudo installed (in venv) needed packages (within the project’s virtual environment), for example: certifi, chardet, Django…, …. After creating ’static’ in the settings.py, on the linode server, I tried to collect static : ~$ python manage.py collectstatic BUT I am getting this Error message: enter image description here PastedGraphic-1.tiff Any idea how to fix it? """ /home/..../django/users/models.py", line 16 return f'{self.user.username} Profile' ^ SyntaxError: invalid syntax """ -
Django model FileField is set to "null" instead of url to the file when using Google Cloud Storage
I am running a File manager app on Local machine using Google Cloud Sql Proxy and storing the files in a Google Cloud Storage bucket. The file is being saved in the bucket, but the FileField is set to "null". I want it to show the url by which I can access the file. I am following this answer Configure Django and Google Cloud Storage? I have set the Google Cloud Storage bucket to public. Django Model: class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') Setting.py: #MEDIA_URL = "/media/" #MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'printhub-files' GS_PROJECT_ID = 'preasy-53c43' GS_MEDIA_BUCKET_NAME = 'printhub-files' # GS_STATIC_BUCKET_NAME = '<name-of-static-bucket>' # STATIC_URL = 'https://storage.googleapis.com/{}/'.format(GS_STATIC_BUCKET_NAME) MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_MEDIA_BUCKET_NAME) Expected Result: { "id": 13, "docfile": "https://storage.googleapis.com/bucket/documents/2019/11/03/myfile.pdf", } Actual Result: { "id": 13, "docfile": null, } If I change my Settings.py to (uncomment line 1,2. Comment line 4), the file is saved on my local machine media/ folder, and "docfile" is set to the bucket url: MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #DEFAULT_FILE_STORAGE = 'storages.backends.gcloud.GoogleCloudStorage' GS_BUCKET_NAME = 'printhub-files' GS_PROJECT_ID = 'preasy-53c43' GS_MEDIA_BUCKET_NAME = 'printhub-files' # GS_STATIC_BUCKET_NAME = '<name-of-static-bucket>' # STATIC_URL = 'https://storage.googleapis.com/{}/'.format(GS_STATIC_BUCKET_NAME) MEDIA_URL = 'https://storage.googleapis.com/{}/'.format(GS_MEDIA_BUCKET_NAME) I get the output: { "id": 13, "docfile": "https://storage.googleapis.com/bucket/documents/2019/11/03/myfile.pdf", } -
Looping through Amadeus API using Django
I have fetched data into my template in Django But Looping though it has been a serious issue. How should get the value like departure, iataCode and likes. [{'type': 'flight-offer', 'id': '1572734309519-939507600', 'offerItems': [{'services': [{'segments': [{'flightSegment': {'departure': {'iataCode': 'LOS', 'terminal': 'I', 'at': '2020-01-01T23:30:00+01:00'}, 'arrival': {'iataCode': 'CDG', 'terminal': '2E', 'at': '2020-01-02T06:00:00+01:00'}, 'carrierCode': 'AF', 'number': '149', 'aircraft': {'code': '789'}, 'operating': {'carrierCode': 'AF', 'number': '149'}, 'duration': '0DT6H30M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'L', 'availability': 9, 'fareBasis': 'LLXSRNG'}}, {'flightSegment': {'departure': {'iataCode': 'CDG', 'terminal': '2E', 'at': '2020-01-02T08:00:00+01:00'}, 'arrival': {'iataCode': 'JFK', 'terminal': '1', 'at': '2020-01-02T10:30:00-05:00'}, 'carrierCode': 'AF', 'number': '22', 'aircraft': {'code': '77W'}, 'operating': {'carrierCode': 'AF', 'number': '22'}, 'duration': '0DT8H30M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'L', 'availability': 9, 'fareBasis': 'LLXSRNG'}}]}, {'segments': [{'flightSegment': {'departure': {'iataCode': 'JFK', 'terminal': '1', 'at': '2020-02-08T18:40:00-05:00'}, 'arrival': {'iataCode': 'CDG', 'terminal': '2E', 'at': '2020-02-09T08:00:00+01:00'}, 'carrierCode': 'AF', 'number': '7', 'aircraft': {'code': '77W'}, 'operating': {'carrierCode': 'AF', 'number': '7'}, 'duration': '0DT7H20M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'N', 'availability': 9, 'fareBasis': 'NLWSRNG'}}, {'flightSegment': {'departure': {'iataCode': 'CDG', 'terminal': '2E', 'at': '2020-02-09T14:10:00+01:00'}, 'arrival': {'iataCode': 'LOS', 'terminal': 'I', 'at': '2020-02-09T20:30:00+01:00'}, 'carrierCode': 'AF', 'number': '104', 'aircraft': {'code': '332'}, 'operating': {'carrierCode': 'AF', 'number': '104'}, 'duration': '0DT6H20M'}, 'pricingDetailPerAdult': {'travelClass': 'ECONOMY', 'fareClass': 'N', 'availability': 9, 'fareBasis': 'NLWSRNG'}}]}], 'price': {'total': '1620.29', 'totalTaxes': '662.29'}, 'pricePerAdult': {'total': '1620.29', 'totalTaxes': '662.29'}}]} {% for … -
Logging status 500 errors to text file
I'd like to log status 500 errors that pop up on my server to a text file. I've implemented the below code in my settings file. Upon the first 500 error, a txt file was created in the directory I expected it to be in, but it's empty. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, 'logfile': { 'class': 'logging.handlers.WatchedFileHandler', 'filename': '/home/jasonhoward/webapps/django/myproject/errors.log' }, 'django': { 'handlers': ['logfile'], 'level': 'ERROR', 'propagate': False, } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': False, } } } Thanks for your help! -
Django "TypeError: '...' object is not iterable"
I need multiple values to be in the courses' contacts, for example phone, facebook etc. I'm overriding create method to make writable nested fields. Everything works fine with "branches". I'm confused because I can't get why Contact is not iterable. Models.py: class Branch(models.Model): latitude = models.CharField(max_length=50) longitude = models.CharField(max_length=50) address = models.CharField(max_length=100) class Meta: ordering = ['latitude'] def __str__(self): return self.address class Contact(models.Model): type = models.IntegerField(choices=TYPE, default=1) value = models.CharField(max_length=100, null=False) class Meta: ordering = ['type'] def __str__(self): return "{} {}".format(self.type, self.value) class Course(models.Model): ... branches = models.ForeignKey(Branch, on_delete=models.CASCADE, null=False, default=True) contacts = models.ForeignKey(Contact, on_delete=models.CASCADE, null=False, default=True) class Meta: ordering = ['name'] def __str__(self): return self.name Serializers.py: class CourseSerializer(serializers.ModelSerializer): ... branches = BranchSerializer(many=True) contacts = ContactSerializer(many=True) class Meta: model = Course fields = ['name', 'description', 'category', 'logo', 'contacts', 'branches'] def create(self, validated_data): branches_data = validated_data.pop('branches') contacts_data = validated_data.pop('contacts') course = Course.objects.create(**validated_data) for branches in branches_data: branch = Branch.objects.create(**branches) course.branches = branch for contacts in contacts_data: contact = Contact.objects.create(**contacts) course.contacts = contact return course -
pip install mysqlclient does'nt work on linux host
Now i upload my project into the linux host and install my packages with host terminal after this when i want runserver this error doesn't allow me for complete uploading when I run pip install mysqlclient this error show off : Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/mahdiade/virtualenv/portfolio/3.7/bin/python3.7_bin -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install- what's the problem? -
Attach Div to Th id / django forloop counter issue
I have a table that looks like this: {% for object in object_list %} <tr> {% for object in object_list %} <td id="destination">{{ forloop_counter }}</td> {% endfor %} </tr> {% endfor %} and I am using this function to attach the bar to the th. function MoveDiv() { var fragment = document.createDocumentFragment(); fragment.appendChild(document.getElementById('bar')); document.getElementById('destination').appendChild(fragment); } I wanted to use the foorloop counter to assign an id to each cell. But the forloop counter populates the cells of the same column with the same id. What else can I try to assign a unique id to each cell? Thank you -
Date does not conform to the required format
I am creating a form, and this form has a date that should be in the format "dd / mm / yyyy", but when I save the date in this format the following error appears: The specified value "11/02/2019" does not conform to the required format, "yyyy-MM-dd". models.py: class Example(models.Model) date = models.DateField(null=False, default=date.today) The form i'm calling in html: {% render_field form.date type="date" %} settings.py: DATE_INPUT_FORMATS = ['%d/%m/%Y'] LANGUAGE_CODE = 'pt-br' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I need the date to be in the format "dd / mm / yyyy", could someone help me? -
How can run django tests in Pycharm Pro, getting ImproperlyConfigured and AppRegistryNotReady errors
I am having issues running django tests in PyCharm Pro. I am able to run python manage.py runserver just fine. I am able to migrate, makemigrations, manage.py test just fine. Actually, everything with manage.py runs as expected. Whenever I run tests in PyCharm (by clicking the green run button), I get this 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. I have done several things to fix this: I have, in my test file, put this: import os os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' (with mysite being the correct dir I promise) I have a settings file and a wsgi file, and my wsgi file does set the DJANGO_SETTINGS_MODULE: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings") application = get_wsgi_application() The only thing that has taken me out of this error was by setting up the configuration for that test class by going to Edit Configuations -> Environment -> Environment Variables and adding the DJANGO_SETTINGS_MODULE there. This only gets me a different error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Plus, I have to do this for every test class and I can't run individual tests in the class, but must rather run the entire … -
Django: How to automatically refresh page after session variable has changed?
I am rendering my nav bar using just html On my nav bar I am showing the number of items current in my shopping cart via request.session.cart_items where cart_items is my session variable When I add items to my cart my cart_items changes, and I see that indeed it has changed when I use print(request.session.cart_items) The problem is that my html only shows the updated request.session.cart_items when I refresh the page. How can I make the page refresh automatically once there has been a change to request.session.cart_items? Here is my navbar.html <nav class="main-nav"> <ul> <li> <a href="/">Painting Website</a> </li> <li> <a href="/">{{ request.session.cart_items}}</a> </li> </ul> </nav> Here is also my CartUpdateAPIView(APIView) from my views.py if that helps class CartUpdateAPIView(APIView): permission_classes = [permissions.AllowAny] def get(self, request, pk=None, *args, **kwargs): product_id = request.get('product_id') product_obj = Painting.objects.get(pk=product_id) cart_obj, new_obj= Cart.objects.new_or_get(request) #remove from cart if already in cart if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) #add to cart if not in cart already else: cart_obj.products.add(product_obj) #adding to many-to-many return redirect("cart-api:cart-list") def post(self, request, pk=None, *args, **kwargs): product_id = request.data['products'][0] #to make sure that product_id is actually coming through if product_id is not None: try: #getting an instance of the painting from the Painting model product_obj = … -
Django `ModuleNotFoundError: No module named 'config'` in Zeppelin notebook
I'm trying to run django.setup() inside Apache Zeppelin. Previously, I have done this successfully in both Jupyter and Zeppelin. Check my Python env. %python sys.executable '/Users/layne/.pyenv/versions/neurodb-py3.7/bin/python' Set my working directory. $ cd ~/Desktop/NeuroDB Make sure working directory is accessible. %python sys.path.append("/Users/layne/Desktop/NeuroDB") %python import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local") django.setup() ERROR Traceback (most recent call last): File "/tmp/zeppelin_python-1811280867650127013.py", line 307, in <module> exec(code, _zcUserQueryNameSpace) File "<stdin>", line 4, in <module> File "/Users/layne/.pyenv/versions/neurodb-py3.7/lib/python3.7/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/Users/layne/.pyenv/versions/neurodb-py3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 79, in __getattr__ self._setup(name) File "/Users/layne/.pyenv/versions/neurodb-py3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/Users/layne/.pyenv/versions/neurodb-py3.7/lib/python3.7/site-packages/django/conf/__init__.py", line 157, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/Users/layne/.pyenv/versions/3.7.3/lib/python3.7/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 953, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'config' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/tmp/zeppelin_python-1811280867650127013.py", line 319, in <module> raise Exception(traceback.format_exc()) Exception: Traceback (most recent call last): File "/tmp/zeppelin_python-1811280867650127013.py", line 307, in <module> … -
OperationalError at / no such table: blog_post_categories
I'm trying to add category section to my blog pet-project; I feel that I almost there, but on the last part of work it showed me an error: "OperationalError at / no such table: blog_post_categories" My models.py class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) categories = models.ManyToManyField('Category', related_name='posts') def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) class Category(models.Model): name = models.CharField(max_length=20) My views.py def home(request): content = { 'posts': Post.objects.all() } return render(request, 'blog/home.html', content) def blog_category(request, category): posts = Post.objects.filter( categories__name__contains=category ).order_by( '-created_on' ) content = { 'category': category, 'posts': posts } return render(request, 'blog/blog_category.html') I don't really understand why, but debugger shows that it is something wrong in base.html on line 0 "In template /media/john/DATA/DJANGO/WORKING/blog/templates/blog/base.html, error at line 0" -
How to call a model's method before saving a serializer in Django Rest Framework?
I have a model where I am trying to create an object using DRF. The model class has a method which I would like to call before saving the serializer. Something like this: class MyModel(models.Model): ... def do_something(self): ... The serializer code: serializer = MyModelSerializer(data=request.data) serializer.obj.do_something() # Does not work serializer.save() Hopefully, you guys get the idea. -
Django: How to connect CheckboxSelectMultiple with an CharField or IntegerField
My question is how can I connect with each CheckboxSelectMultiple Item another Charfield or IntegerField? I have a typical code structure, a Model is used in a Form that is then saved in the views. class DocAideForm(forms.ModelForm): class Meta: model = DocAide fields = [..., 'drug', 'int_list'] widgets = { ..., 'drug': forms.CheckboxSelectMultiple() } In views.py I do it like this: if doc_aide_from.cleaned_data['drug']: p = Prescription(patient=patient) p.qty = doc_aide_from.cleaned_data['int_list'] p.save() p.drug.add(*list(doc_aide_from.cleaned_data['drug'])) This works fine but they are not connected with each Drug Item. I want the Drug to be shown in the template with the Qty Charfield or IntegerField in the same place. Like this for each Drug: x Paracetamol Qty: ___1____ How can that be accomplished. -
The home page translation link is static and is not used to translate all pages
I have a problem I hope to solve it as I display in the navbar languages used in the site and I want whenever you click on the language the page appears with the translation in all pages and not only the main page ,with the translation link changes with each page http://127.0.0.1:8000/fr/ http://127.0.0.1:8000/fr/our-company So add on the home page link. How to fixed the link on the home page so that the translation is displayed for all pages and keep on the same page translated Navbar home page in all pages <ul class="navigation__dropdown-wrap--language"> <li> <a data-culture="ar" data-lang="True" href="/">العربية</a> </li> <hr> <li> <a data-culture="en" data-lang="True" href="/en/" lang="en">English</a> </li> <hr> <li> <a data-culture="fr" data-lang="True" href="/fr/" lang="fr">français</a> </li> <hr> </ul> -
AptUrl Error when I try to use module for input selection in django-forms
On my django form I want to have inputs that have several options so I created a file names "choices.py" I basically followed what this guy does here https://stackoverflow.com/a/24404791/8993840 Here's the code forms.py class Createjob(forms.Form): title = forms.CharField(label= "", help_text= "") job_sector = forms.ChoiceField(choices=JOB_SECTOR, label="", initial='', widget=forms.Select(), required=True) location = forms.ChoiceField(choices=LOCATION, required=True) experience_level = forms.ChoiceField(choices=EXPERIENCE_LEVEL, required=True) description = forms.CharField(widget=forms.Textarea) models.py class Emprego(models.Model): id = models.AutoField(primary_key=True) # Id_autogerated title = models.CharField(max_length=70) description = models.CharField(max_length=200) created_at = models.DateTimeField(auto_now_add=True) publisher = models.ForeignKey(Empresa, on_delete=models.CASCADE) location = models.IntegerField(choices=LOCATION, default=1) # Pode ser Remote, no Local da empresa ou noutra sede ou sth else # Professional Details type_job = models.CharField(max_length=50) # Contrato, part-time, etc experience_level = models.IntegerField(choices=EXPERIENCE_LEVEL, default=1) job_sector = models.IntegerField(choices=JOB_SECTOR, default=1) # IT, Economy work_functions = models.CharField(max_length=50) # as Executive, worker, it guy, etc file = models.FileField(blank=True) # Can post a PDF with more details of the job, but it's totally optional def __str__(self): return str(self.id) + self.title choices.py from AptUrl.Helpers import _ JOB_SECTOR = ( (1, _("Software Development")), (2, _("Analyst")), (3, _("Project Management")), (4, _("Sales")), (5, _("Administrative")), (6, _("Finance")), (7, _("Art/Design")), (8, _("Human Resources")), (9, _("Medical/Healthcare")), (10, _("Cashier")) ) ... When I try to run the following error appears: File "/home/dias/Desktop/Universidade/TPW/jobber/job_app/choices.py", line 1, in … -
Redirect from one page to another by AJAX request, passing parameters with Django
I have a table in a view where according of the element Id which is clicked, that view redirect to another via Ajax request to a Django Rest Framework endpoind and render a dasboard with Chartjs, with dynamic data and sending an user_id. I make the request success and get back the results of the endpoing as json format, but when it should redirect to the other page, it redirects to an empty html template displaying the json result but without my html template. This probably is a really dummy problem, but I can't figure out the error. This answer have an useful code, but hasn't the behaviour that I need My project structure is as below: core --api --core --static --web (...and other folders) These are the routes related: core/urls.py urlpatterns = [ url(r'^socialanalyzer/recent_search_twitter/$', RecentSearchTwitterView.as_view(), name='recent_search_twitter'), url(r'^socialanalyzer/timeline_search_twitter/$', TimelineSearchTwitterView.as_view(), name='timeline_search_twitter') ] api.py/urls.py urlpatterns = [ url(r'^api/search/recent_search/user/<int:user_id>/social_network/<int:social_network_id>', SearchViewSet.as_view({'post': 'recent_search'}), name='recent_search'), url(r'^api/search/word_details/user/<int:user_id>/social_network/<int:social_network_id>/word/<string:word>', SearchViewSet.as_view({'post': 'word_details'}), name='word_details') ] So in my web/views.py, i need to navigate from: RecentSearchTwitterView (recent_search_twitter.html) to TimelineSearchTwitterView (word_searched_details_twitter.html) In that sense, in recent_search_twitter.html I have a table with each row as below: <td><a href="" onclick='wordSearchedDetail("{{key.word}}")'><b>{{key.word}}</b></a></td> That call to wordSearchedDetail where is in: static/js/custom.js function wordSearchedDetail(word){ $.ajax({ url:'/socialanalyzer/timeline_search_twitter/', type: 'GET', data: … -
Django postgres connector psycopg2
As i run pip install psycopg2 in my django virtualven in windows it start downloading and at the end of downloading this Error comes |████████████████████████████████| 430kB 61kB/s ERROR: Command errored out with exit status 1: command: 'c:\users\tusha\appdata\local\programs\python\python38-32\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\setup.py'"'"'; file='"'"'C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\pip-egg-info' cwd: C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\ Complete output (23 lines): running egg_info creating C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\pip-egg-info\psycopg2.egg-info writing C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\pip-egg-info\psycopg2.egg-info\PKG-INFO writing dependency_links to C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\pip-egg-info\psycopg2.egg-info\dependency_links.txt writing top-level names to C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\pip-egg-info\psycopg2.egg-info\top_level.txt writing manifest file 'C:\Users\tusha\AppData\Local\Temp\pip-install-hoeubopv\psycopg2\pip-egg-info\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPIe install the PyPI 'psycopg2-binary' package instead. st' file (also at For further information please check the 'doc/src/install.rst' file (also at <http://initd.org/psycopg/docs/install.html>). egg_info Check the logs for full command outpu ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. so how to solve this ERROR -
Is converting timestamp to datetime in django will convert datetime by default to datetime in UTC
I am creating an app which will use peoples from different timezones. I have a model class Fixture(models.Model): fixture_id =models.IntegerField(primary_key=True) event_date = models.DateTimeField(null=True) I want while creating objects from this model that event_date field save datetime object in UTC to convert it in user's timezone while show him this data in front-end. In django documentation i read that When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms. Now i am creating an object b = Fixture.objects.create(fixture_id = fixture, event_date = datetime.datetime.fromtimestamp(variable_contained_timestamp)) Is according django documentation in event_date field will be stored datetime object in UTC not in datetime object with my database time zone -
Can't access foreignKey in template
I'm trying to access a foreignKey object in my template, but it doesn't show anything at all. I'd like to show the url to the ImageField saved in the db Models.py class Usertasks(models.Model): TaskID = models.CharField(max_length=55) user = models.ForeignKey(User, unique=False, on_delete=models.CASCADE) TaskStatus = models.CharField(max_length=15, default="missing") class TaskImages(models.Model): UserTasks = models.ForeignKey(Usertasks, related_name='images', on_delete=models.CASCADE) image = models.ImageField() views.py def task_info(request, taskid): task = Usertasks.objects.get(TaskID=taskid) taskhtml = Usertasks.objects.filter(TaskID=taskid) files = os.listdir(task.OutputPath) fullpath = task.OutputPath print(files) for img in files: imagepath = fullpath + "/" + img task_image = TaskImages() task_image.UserTasks = task task_image.image = imagepath task_image.save() return render(request, 'dashboard/task.html', {'query':taskhtml}) html {% for item in query.image_set.all %} <img src="{{ item.url }}"> {% endfor %} -
problem with pagination in function based view in django
can’t understand how to use pagination in this kind of function. def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products, }) -
Updating to non-standard database in DRF
Using Django Rest Framework, how to execute update/PUT calls to a non-standard database? In my Django project I'm using a separate database for the application data: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'bookstore': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'bookstore.sqlite3'), } } I use the ModelSerializer and ModelViewSet to automatically create the API for me. I loop over the models to automatically generate all the Serializers and ViewSets (quite a big number of tables), the generated classes end up looking like this: ModelSerializer: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' ModelViewSet: class BookViewSet(viewsets.ModelViewSet): queryset = Book.objects.using('bookstore').all() serializer_class = BookSerializer I needed to add the using('bookstore') here to make this work. Reading (GET) works fine. When I try to do a PUT update, I get a no such table: book Sqlite error. It seems like the update isn't routed to the bookstore database. For completeness, I use these loops to generate the ModelSerializer and ModelViewSets from the models: ModelSerializer, generator: models = dict(apps.all_models['api']) for name, model in models.items(): class_name = name[:1].upper() + name[1:] + 'Serializer' Meta = type('Meta', (object, ), {'model': model, 'fields': '__all__'}) print(class_name) globals()[class_name] = type(class_name, (serializers.ModelSerializer,), {'Meta':Meta, }) ModelViewSet, generator: models …