Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 2.0: sqlite IntegrityError: FOREIGN KEY constraint failed
I'm working on adding Django 2.0 support to the django-pagetree library. During automated testing, using an sqlite in-memory database, I'm getting a bunch of errors like this: File "/home/nnyby/src/django-pagetree/pagetree/tests/test_models.py", line 638, in setUp 'children': [], File "/home/nnyby/src/django-pagetree/pagetree/models.py", line 586, in add_child_section_from_dict ... File "/home/nnyby/src/django-pagetree/venv/lib/python3.5/site-packages/django/db/backends/base/base.py", line 239, in _commit return self.connection.commit() django.db.utils.IntegrityError: FOREIGN KEY constraint failed This is noted in the Django 2.0 release notes: https://docs.djangoproject.com/en/2.0/releases/2.0/#foreign-key-constraints-are-now-enabled-on-sqlite From that description, which I don't fully understand, this shouldn't apply for test databases that aren't persistent, right? Wouldn't my sqlite test db get created with the appropriate options when using Django 2.0? The app settings I'm using for testing are here: https://github.com/ccnmtl/django-pagetree/blob/master/runtests.py -
using a if statement in a generic detail view
I am having trouble to figure out how to manage my error: my app is built that way : a user create a project the user is redirected to a project detail page The user is asked to create a team and add members to that project The user is again redirected to the project detail page rendering now the team name and a list of all the team members. My problem is that I wanted to add a context_data to render in my HTML def get_context_data(self, **kwargs): context = super(ProjectDetailView, self).get_context_data(**kwargs) team_name = Project.objects.get(id=self.kwargs['pk']).team_id.members.all() context['team_name'] = team_name return context but now when I create a project since there is no team and member yet, I am getting an error 'NoneType' object has no attribute 'members' How can I do? is there a way to add a if statement in a view ? -
Django sometimes gives 404 and sometimes gives 200
With the same configuration in Django, visiting the same URL served sometimes gives me a 404 while it will give me a 200 later. Any idea how would this happen and how to solve it? -
Django Model Inheritance - get child
Is there a way to access the actual child of the base model, means: Staying with the example from the django Docs, let's assume I am modeling different delivery restaurants, that just have in common name all have a deliver method as of this: class Place(models.Model): name = models.CharField(max_length=10) class Pizzeria(Place): topping = models.CharField(max_length=10) tip = models.IntegerField() def deliver(self): deliver_with_topping(self.topping) ask_for_tip(self.tip) class Shoarma(Place): sauce = models.CharField(max_length=10) meat = models.CharField(max_lenght=10) def deliver(self): prepare_sauce_with_meat(self.sauce, self.meat) I would now like to execute: Place.objects.get(name="my_place").<GENERIC_CHILD>.deliver() i.e. I don't need to know what the place is actually, just the common deliver method. The model then 'knows' what to call. Is there something like <GENERIC_CHILD>? -
unable to download csv from django admin on HEROKU
This is my code for downloading csv, pretty straight forward, @admin.register(User) class UserAdmin(admin.ModelAdmin): actions = ['download_csv_file','send_mail'] def download_csv_file(self, request, queryset): import StringIO f = StringIO.StringIO() import csv writer = csv.writer(f) writer.writerow(['first name','mobile','email','gender']) for i in queryset: print(i) writer.writerow([i.first_name,i.mobile,i.email,i.gender]) f.seek(0) from django.http import HttpResponse response = HttpResponse(f, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=User-info.csv' return response This works perfectly on my localhost. But I am unable to download csv when I deployed it on heroku. It gives a 500 interval server error. This is the corresponding log record, 2017-12-03T14:36:06.940950+00:00 heroku[router]: at=info method=POST path="/admin/bookings/user/" host=xxxxx-xx.herokuapp.com request_id=xxxx fwd="xx.xx.xx.xx" dyno=web.1 connect=0ms service=47ms status=500 bytes=234 protocol=https I couldnt get Why is it happening on heroku. Where is the problem? -
Which available UI JavaScript framework should I use to build magazine editor?
I would like to build a single page web application in which user will create its own magazine in predefined templates. The main features which it should have include: upload images or obtain them from social networks move, rotate, scale images fill in texts print final work in pdf The backend part will be written in Django and I am considering one of UI Javascript framework for front-end. Could you please give me an advice which of the following would you prefer: Angular, React or Ember? Or do you have some other framework in mind which would suit for this project? -
django, make pk's child form_class in CBV
I can't understand how to make pk's child object's form in UpdateView for an instance model.py class User(models.Model): id name class A(models.Model): user = models.ForeignKey(User,related_name='shipping_user',on_delete=models.CASCADE) a_name = char form.py class A_Form(ModelForm): class Meta: model=User fields = ('a_name',) widgets = {'a_name': forms.TextInput()} view.py class UPDATE_A(UpdateView): """ update user's A in this class """ model = A form_class = A_Form template_name = "template" success_url = "success_url" def form_valid(self, form): if form.is_valid: form.save() print "success!!" return super(UPDATE_A, self).form_valid(form) and urls.py #<pk> gets user's ID url(r'^update_user_a/(?P<pk>\d+)/$', views.UPDATE_A.as_view()), What I want is ,in view function, finding the A object from user_id given url parameter. And make modelform of A. But I don't know how to make it... *The relation between User and A is 1 to 1. Anyone knows solutions? -
Django-channels - recieve data based on url
I'm very new to django-channels so this is probably a very simple question. On our website, there is a permanent button "Messages" in the header. I want user to be notified about new message immediately. So I use channels for this purpose. If there is a new message created, I send a number of not readed conversations through channels to client: class Message(..): def save(...): notify_recipient(self) def notify_recipient(self): Group('%s' % self.recipient).send({ "text": json.dumps({ "message":{"text":truncatechars(self.text,100)}, "unreaded_conversations":Conversation.objects.get_unreaded_conversations(self.recipient).count(), }), }) And in base.html: const webSocketBridge = new channels.WebSocketBridge(); webSocketBridge.connect('/notifications/'); webSocketBridge.listen(function (action, stream) { console.log(action, stream); var conversations_sidebar = $('#id_conversations_sidebar'); var messages_list = $('#messagesList'); if (action.unreaded_conversations) { $('#id_unreaded_conversations_count').text(action.unreaded_conversations); } On the other hand, there is a page /chat/detail/<username>/ where users chat with each other. This chat should be live so I need to recieve messages through channels. For now, I've added rendered message to the notify_recipient method but the problem is that it has to render the message allways, even when user is not on this /chat/detail/<username>/ url which is not efficient. Do you know how to recieve rendered messages only when user is in the current chat? routing.py @channel_session_user def message_handler(message): message.reply_channel.send({"accept": True}) @channel_session_user_from_http def ws_connect(message,): Group("%s" % message.user).add(message.reply_channel) message.reply_channel.send({"accept": True}) channel_routing = … -
django : table doctor_dschedule has no column named morning_2(Django version1.11)
I am using python and when changing a model in my program i came through this error. I tried to change model's column from morning_1 to morning_2 and used migrate -fake to migrate .But when using the existed database the error says there is no morning_2 column.So i am quite confused,and don't know what to do. -
ImportError: No module named 'django.contrib.admindjango' creating django login app
I am working from a django tutorial on creating a social login system, and I've been getting the error below. The tutorial: https://medium.com/@jainsahil1997/simple-google-authentication-in-django-58101a34736b The error: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/Users/xxxx/Documents/login/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/xxxx/Documents/login/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/Users/xxxx/Documents/login/env/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/xxxx/Documents/login/env/lib/python3.5/site-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Users/xxxx/Documents/login/env/lib/python3.5/site-packages/django/apps/config.py", line 120, in create mod = import_module(mod_path) File "/Users/xxxx/Documents/login/env/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 944, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "<frozen … -
wagtail formbuilder show 'required' in template
I am implementing a Formbuilder form in a wagtail website, but like to get the required value while looping over the form fields so I can show a required icon. The required seems to be in the query, but nothing I try shows me a result. -
How to validate on read only field in Django Rest Framework
I'm trying to add a vote functionality to the code found in tutorial of Django Rest Framework. On top of Snippet model, I added a Vote model: class Vote(models.Model): created = models.DateTimeField(auto_now_add=True) voter = models.ForeignKey(User, on_delete=models.CASCADE) snippet = models.ForeignKey(Snippet, related_name='votes', on_delete=models.CASCADE) class Meta: ordering = ('created',) In my serializer, I'm trying to validate the fact that user cannot vote more than once and cannot vote for his own snippet: class VoteSerializer(serializers.HyperlinkedModelSerializer): voter = serializers.ReadOnlyField(source='voter.username',validators=[UniqueValidator(queryset=Vote.objects.all(), message=already_voted)]) snippet = serializers.PrimaryKeyRelatedField(queryset=Snippet.objects.all()) def validate(self, data): snippet = data.get('snippet') voter = data.get('voter') if voter==data['snippet'].owner: raise serializers.ValidationError(u"Voter cannot vote for himself.") return data Voter field must be read-only. Problem is that ReadOnlyField is not available in data structure. How can I validate with read only field? -
Best practice setup for two websites with different style sheets and templates, but similar Django back end
I'm working on a Django back end that will be used by two websites (i.e., a job board for non-profits and a job board for for-profit companies), but I'm not sure how this is best structured to make it easy to push/pull updates to the two websites. The Django code for the websites is highly similar (let's say over 95% overlap), but the websites have slightly different templates and separate CSS style sheets, in order to give each a distinct look and feel. My inclination would be to set this up as a single Django project that stores the CSS style sheets for both websites, has a different templates folder for each website, and has multiple settings files (e.g., base, production_fprofit, production_nprofit). To facilitate any current or future differences in the back end, a settings variable would indicate the platform for which the code is used (e.g., FPROFIT = True/FPROFIT = False) and this variable is called when necessary (e.g., if settings.FPROFIT == True: self.context_dict["profile_form"] = TRUE). Whenever the Django code changes, the code is pushed to GIT and pulled by the two platforms - each running on a separate virtual host, with their own testing, staging, and production environments. … -
Sending Django/Python with image rendered in html template?
I would like to send a HTML-Mail with Python-Django including a picture at a specified place within my template ExampleMail.html ExampleMail.html <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>MyMail</title> </head> <body> <table width="800"> <tr> <td align="right"><img src={{mylogo}} alt="no picture...?" align="right"></td> </tr> </table> <table width="800"> <tr> <td align="left"> {{name}} {{user}}<br> </td> </table> </body> </html> When sending the Mail to me as a test I get the picture as attachement but not in the ExampleMail.html template. This is how I send the Mail with myMailExample.py and render my mail with params. myMailExample.py from django.core.mail import EmailMultiAlternatives from email.mime.image import MIMEImage from django.template.loader import render_to_string def send_mail_with_picture(): params = {'mylogo':'mylogo.jpg'} html_body = render_to_string('ExampleMAIL.html', params) text_body = render_to_string('ExampleMAIL.html', params) img_data = open("mylogo.jpg", 'rb').read() img = MIMEImage(img_data) img.add_header('Content-ID', 'mylogo') img.add_header('Content-Disposition', 'inline', filename="mylogo.jpg") email = EmailMultiAlternatives( subject="Here is your mail", body=text_body, from_email='noreply@example.com', to=['info@dldlkjgklflskdjf.com',] ) email.attach_alternative(html_body, "text/html") email.mixed_subtype = 'related' email.attach(img) email.send(fail_silently=False) Can you help me on this to render the mail with the picture in place of the table and not as attachement? HA -
Django : how to extract items of another table from one table if they are related by foreign key
I have two tables : User and Details(which includes details of books).They are linked with each other by a foreign key as shown: class Details(models.Model): user= models.ForeignKey(settings.AUTH_USER_MODEL, null=True) BName= models.CharField(max_length=200) BPublisher= models.CharField(max_length=200) BEdition= models.CharField(max_length=100) BAuthor= models.CharField(max_length=200) BClass= models.CharField(max_length=100) Now i need to extract all the books from the table-Details posted by distinct user. How can I do this ? The Filed in Django admin looks like :enter image description here -
HTTP 404, Not Found. Django
I am developing an e-learning website on django 1.11. When going through the website, I am getting HTTP 404, Not Found in the terminal (as shown in the image). This is not the usual 404 error caused by misspelling of the url, because on the browser side the page renders properly (but sometimes keeps on waiting and waiting) and I am not sure what is causing the error. The error looks like this: Error in Powershell In this image, we can see that HTTP returns 200, when asked for subject list page. When the subject select page is requested it first returns 200 (success) but then it returns two 404 errors (I am not sure where they are coming from.) This error has not stopped the server but I do not know whether this error is harmful for production or not. What kind of error is this? How can I get rid of this? Codes: models.py class Subject(models.Model): subject_name = models.CharField(max_length=120) slug = models.SlugField(unique=True, blank=True) faculty = models.CharField(max_length = 120, blank=True) poster_image = models.ImageField(upload_to = None, null=True, blank=True, width_field = "width_field", height_field = "height_field") height_field = models.IntegerField(default = 0, blank=True, null=True) width_field = models.IntegerField(default = 0, blank=True, null=True) def get_subject_select_url(self): … -
Make all fields of ManyToMany Model appear in form
I am all new to coding, for my first project I decided to work with Django. I am coding a web application that will permit a user to create specification sheets very easily, by completing a form that creates a pdf document (a specification sheet). My main model is "Fiches", from which I have m2m links to my other models that can contain 1 or several attributes each. All my codes are below. model.py (not finished setting the parameters, just to have something to work with) -- coding: utf-8 -- from django.db import models from django.conf import settings from django.utils import timezone class Utilisateurs(models.Model): nom = models.CharField(max_length=200) prenom = models.CharField(max_length=200) pays = models.CharField(max_length=200) class Calibres(models.Model): calibre = models.CharField(max_length=200) tolerance = models.CharField(max_length=200) class Additifs(models.Model): denomination_FR = models.CharField(max_length=200) denomination_EN = models.CharField(max_length=200) denomination_ES = models.CharField(max_length=200) class Ingredients(models.Model): denomination_FR = models.CharField(max_length=200) denomination_EN = models.CharField(max_length=200) denomination_ES = models.CharField(max_length=200) class Formes(models.Model): denomination_FR = models.CharField(max_length=200) Denomination_EN = models.CharField(max_length=200) Denomination_ES = models.CharField(max_length=200) class DimensionsProduit(models.Model): denomination_FR = models.CharField(max_length=200) denomination_EN = models.CharField(max_length=200) denomination_ES = models.CharField(max_length=200) Valeur = models.CharField(max_length=200) class Conditionnements(models.Model): primSec_FR = models.CharField(max_length=200) primSec_EN = models.CharField(max_length=200) primSec_ES = models.CharField(max_length=200) nature_FR = models.CharField(max_length=200) nature_EN = models.CharField(max_length=200) nature_ES = models.CharField(max_length=200) compose_FR = models.CharField(max_length=200) compose_EN = models.CharField(max_length=200) compose_ES = models.CharField(max_length=200) couleur_FR = models.CharField(max_length=200) … -
Django, ModuleNotFoundError: No module named 'mysqlclient'
After I set up the virtual environment, I activated it and pip installed a few packages, with pip freeze, I also get what I installed in this virtual-envs: (django-ml) C:\Users\LyuMing\Envs\django-ml\aspolimi> pip freeze Django==1.11.7 django-toolbelt==0.0.1 gunicorn==19.7.1 Jinja2==2.10 MarkupSafe==1.0 mysqlclient==1.3.12 numpy==1.13.3 psycopg2==2.7.3.2 PyMySQL==0.7.11 python-dateutil==2.6.1 But when I try to load the module in the editor, or django shell, for instance, when I try to load mysqlclient, there is an error: ModuleNotFoundError: No module named 'mysqlclient' (django-ml) PS C:\Users\LyuMing\Envs\django-ml> python manage.py shell >>>import mysqlclient Traceback (most recent call last): File "<console>", line 1, in <module> ModuleNotFoundError: No module named 'mysqlclient' then I import sys module to check PATH variables, These modules I installed are in the system path, but why can't I import them? ['C:\\Users\\LyuMing\\Envs\\django-ml\\aspolimi', 'C:\\Users\\LyuMing\\Envs\\django-ml\\Scripts\\python36.zip', 'C:\\Use rs\\LyuMing\\Envs\\django-ml\\DLLs', 'C:\\Users\\LyuMing\\Envs\\django- ml\\lib', 'C:\\Users\\LyuMing\\Envs\\django-ml\\S cripts', 'c:\\python36\\Lib', 'c:\\python36\\DLLs', 'C:\\Users\\LyuMing\\Envs\\django-ml', 'C:\\Users\\LyuMing\\Envs\\dj ango-ml\\lib\\site-packages'] -
How to show content by scrolling down?
I have written some html code for my webpage in which multiple images are shown. the problem is, all the images are loaded at the starting itself. I want to change that to show extra images by scrolling down. How to do that with jQuery? The code is: {% extends "base.html" %} {% load staticfiles %} {% block content %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <h2>Pictures of Coffee</h2> <div class="row"> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/04LDEYRW59.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/90V03Q5Y60.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/O83SF2RB6D.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/5JVPSVP7EI.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/C5Y10KIIHA.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/YSSFRY5B25.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/04LDEYRW59.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/90V03Q5Y60.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/O83SF2RB6D.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/5JVPSVP7EI.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/C5Y10KIIHA.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/YSSFRY5B25.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/04LDEYRW59.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/90V03Q5Y60.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/O83SF2RB6D.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/5JVPSVP7EI.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/C5Y10KIIHA.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/YSSFRY5B25.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/04LDEYRW59.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/90V03Q5Y60.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/O83SF2RB6D.jpg" alt=""></div> <div class="col-lg-4 col-xs-6 thumbnail"><img src="https://d2lm6fxwu08ot6.cloudfront.net/img-thumbs/960w/5JVPSVP7EI.jpg" … -
django convert list to query set
i have a list [<Upload: 33-bb6f5d9a98604450>, <Upload: 35-bb6f5d9a98604450>, <Upload: 30-bb6f5d9a98604450>, <Upload: 31-bb6f5d9a98604450>, <Upload: 34-bb6f5d9a98604450>] which has been generated by ques = list(sorted(Upload.objects.filter(unique_id=tdetail), key=lambda x: random.random())) <Upload: 33-bb6f5d9a98604450> here Upload is the model and 33-bb6f5d9a98604450 is the slug of model upload how can we extract Upload model values from this list -
Not able to load images from static folder of Django even after proper configuration
HTML Page: <body> {% load static %} <section class="hero is-success is-fullheight"> <div class="hero-body"> <div class="container has-text-centered"> <div class="column is-4 is-offset-4"> <h3 class="title has-text-grey">Login</h3> <div class="box"> <figure class="avatar"> <img src="{% static 'images/abc.png' %}"> </figure> Settings.py configuration # Static files (CSS, JavaScript, Images)STATIC_URL = '/static/' STATIC_URL = '/static/' #STATIC_URL = os.path.join(BASE_DIR, "static/") STATIC_ROOT = '/staticfiles/' #STATIC_ROOT = os.path.join(BASE_DIR, "static/") INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] When i try to load an image using the above configuration. I am unable to get the response. Error is throwing like "GET http://127.0.0.1:8000/static/images/abc.png 404 (Not Found)" Thanks! -
My Django Web gets empty values when I try to use UpdateView to edit data
I am trying to use an Edit button in my website to edit items using UpdateView. The problem is, that when I click edit the forms are staying blank without the previous data data. Under forms I have post.id that I supposed to give him so forms will know which form to get his data... but it doesn't work.. I have no idea why.. serverlist.html- <div class="container"> <br> <center><h1 class="display-4">DevOps Server List</h1></center> <br> <center><button type="button" class="save btn btn-outline-success btn-lg" data-toggle="modal" data-target=".AddServer">Add Server <i class="fa fa-server fa-lg" aria-hidden="true"></i></button></center> <table class="table table-hover table-bordered table-condensed" cellspacing="0" width="1300" id="ServerTable"> <thead> <tr> <th><center> #</center></th> <th><center> Server Name </center></th></center> <th><center> Owner </center></th></center> <th><center> Project </center></th></center> <th><center> Description </center></th></center> <th><center> IP Address </center></th></center> <th><center> ILO </center></th></center> <th><center> Rack </center></th></center> <th><center> Status </center></th></center> <th><center> &nbsp;&nbsp;&nbsp;&nbsp; Actions &nbsp;&nbsp;&nbsp;&nbsp; </center></th></center> </tr> </thead> <tbody> {% for server in posts %} <tr> <div class ="server"> <td></td> <td><center>{{ server.ServerName }}</center></td> <td><center>{{ server.Owner }}</center></td> <td><center>{{ server.Project }}</center></td> <td><center>{{ server.Description }}</center></td> <td><center>{{ server.IP }}</center></td> <td><center>{{ server.ILO }}</center></td> <td><center>{{ server.Rack }}</center></td> <td><h4><span class="badge badge-success">Online</span></h4></td></center> <td> &nbsp;&nbsp;&nbsp;&nbsp; <button type="button" class="btn btn-outline-danger" data-toggle="modal" href="#delete-server-{{server.id}}" data-target="#Del{{server.id}}">Delete <i class="fa fa-trash-o"></i></button>&nbsp; <button type="button" class="btn btn-outline-primary" data-toggle="modal" href="#edit-server-{{server.id}}" data-target="#Edit{{server.id}}"> &nbsp;&nbsp;Edit&nbsp; <i class="fa fa-pencil"></i></button> &nbsp; <div id ="Del{{server.id}}" class="modal fade" role="document"> <div class="modal-dialog" … -
Import external react component from CDN (React Bootstrap Slider)
I have a Django project and I want to use React on it. I have already created my own components and this works, but I dont know how to import third-party components from CDN. To do this, I did: Import React (develop or production version) in the base template: <!-- baseTemplate.html --> {# ReactJs#} <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script> Also import the file where I create my components <!-- baseTemplate.html --> <script src="/one_directory/my_react.jsx" type="text/babel"></script> and create the tag where it will be rendered. <!-- template.html --> <div id="container"></div> And finally render my React components: <!-- my_react.jsx --> ReactDOM.render( <App />, document.getElementById('container') ); This works correctly :) Now, I want to import a third-party component (specifically, it's React Bootstrap Slider) from CDN, but I dont know how. Maybe this is not possible, I dont know. How could I do it? Thank you very much :] -
the miss "meida" path in django-oscar image URL
I m trying django-oscar to build an e-commerce website. I have deployed django-oscar on Heroku (with Amazon S3 as static and media file bucket), the issue is When I try to add a photo for a product on dashboard, The system returns the correct working URL https://s3.amazonaws.com/mybucket/media/cache/XXX/YYY/ZZZ.jpg that works on first page view request. Reload the page. The system returns broken URL: https://s3.amazonaws.com/mybucket/cache/XXX/YYY/ZZZ.jpg (missing 'media' path) any idea about this miss "media"? -
python - mock, patch, start and return_value
When using mock patcher with start() (and stop() later on) - does it matter when I add the return_value? For example - is there a difference between - cls._dm_delete_attachment_patcher = mock.patch.object(DmService, 'delete_attachment') cls._dm_delete_attachment_patcher.return_value = 'some_deleted_attachment_urn' cls._dm_delete_attachment_start = cls._dm_delete_attachment_patcher.start() and - cls._dm_delete_attachment_patcher = mock.patch.object(DmService, 'delete_attachment') cls._dm_delete_attachment_start = cls._dm_delete_attachment_patcher.start() cls._dm_delete_attachment_start.return_value = 'some_deleted_attachment_urn' or maybe it should be - cls._dm_delete_attachment_patcher = mock.patch.object(DmService, 'delete_attachment') cls._dm_delete_attachment_patcher.return_value = 'some_deleted_attachment_urn' cls._dm_delete_attachment_start = cls._dm_delete_attachment_patcher.start() cls._dm_delete_attachment_start.return_value = 'some_deleted_attachment_urn' In my test, seems like the first option failed, and the third did the work. I'm not sure why.